Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67        parent: a reference to the parent expression (or None, in case of root expressions).
  68        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  69            uses to refer to it.
  70        comments: a list of comments that are associated with a given expression. This is used in
  71            order to preserve comments when transpiling SQL code.
  72        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  73            optimizer, in order to enable some transformations that require type information.
  74
  75    Example:
  76        >>> class Foo(Expression):
  77        ...     arg_types = {"this": True, "expression": False}
  78
  79        The above definition informs us that Foo is an Expression that requires an argument called
  80        "this" and may also optionally receive an argument called "expression".
  81
  82    Args:
  83        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 262        if self.comments is None:
 263            self.comments = []
 264        if comments:
 265            self.comments.extend(comments)
 266
 267    def append(self, arg_key, value):
 268        """
 269        Appends value to arg_key if it's a list or sets it as a new list.
 270
 271        Args:
 272            arg_key (str): name of the list expression arg
 273            value (Any): value to append to the list
 274        """
 275        if not isinstance(self.args.get(arg_key), list):
 276            self.args[arg_key] = []
 277        self.args[arg_key].append(value)
 278        self._set_parent(arg_key, value)
 279
 280    def set(self, arg_key, value):
 281        """
 282        Sets `arg_key` to `value`.
 283
 284        Args:
 285            arg_key (str): name of the expression arg.
 286            value: value to set the arg to.
 287        """
 288        self.args[arg_key] = value
 289        self._set_parent(arg_key, value)
 290
 291    def _set_parent(self, arg_key, value):
 292        if hasattr(value, "parent"):
 293            value.parent = self
 294            value.arg_key = arg_key
 295        elif type(value) is list:
 296            for v in value:
 297                if hasattr(v, "parent"):
 298                    v.parent = self
 299                    v.arg_key = arg_key
 300
 301    @property
 302    def depth(self):
 303        """
 304        Returns the depth of this tree.
 305        """
 306        if self.parent:
 307            return self.parent.depth + 1
 308        return 0
 309
 310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 311        """Yields the key and expression for all arguments, exploding list args."""
 312        for k, vs in self.args.items():
 313            if type(vs) is list:
 314                for v in vs:
 315                    if hasattr(v, "parent"):
 316                        yield k, v
 317            else:
 318                if hasattr(vs, "parent"):
 319                    yield k, vs
 320
 321    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 322        """
 323        Returns the first node in this tree which matches at least one of
 324        the specified types.
 325
 326        Args:
 327            expression_types: the expression type(s) to match.
 328
 329        Returns:
 330            The node which matches the criteria or None if no such node was found.
 331        """
 332        return next(self.find_all(*expression_types, bfs=bfs), None)
 333
 334    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 335        """
 336        Returns a generator object which visits all nodes in this tree and only
 337        yields those that match at least one of the specified expression types.
 338
 339        Args:
 340            expression_types: the expression type(s) to match.
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self):
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self):
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self):
 473        return self.sql()
 474
 475    def __repr__(self):
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    def replace(self, expression):
 545        """
 546        Swap out this expression with a new expression.
 547
 548        For example::
 549
 550            >>> tree = Select().select("x").from_("tbl")
 551            >>> tree.find(Column).replace(Column(this="y"))
 552            (COLUMN this: y)
 553            >>> tree.sql()
 554            'SELECT y FROM tbl'
 555
 556        Args:
 557            expression (Expression|None): new node
 558
 559        Returns:
 560            The new expression or expressions.
 561        """
 562        if not self.parent:
 563            return expression
 564
 565        parent = self.parent
 566        self.parent = None
 567
 568        replace_children(parent, lambda child: expression if child is self else child)
 569        return expression
 570
 571    def pop(self):
 572        """
 573        Remove this expression from its AST.
 574
 575        Returns:
 576            The popped expression.
 577        """
 578        self.replace(None)
 579        return self
 580
 581    def assert_is(self, type_):
 582        """
 583        Assert that this `Expression` is an instance of `type_`.
 584
 585        If it is NOT an instance of `type_`, this raises an assertion error.
 586        Otherwise, this returns this expression.
 587
 588        Examples:
 589            This is useful for type security in chained expressions:
 590
 591            >>> import sqlglot
 592            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 593            'SELECT x, z FROM y'
 594        """
 595        assert isinstance(self, type_)
 596        return self
 597
 598    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 599        """
 600        Checks if this expression is valid (e.g. all mandatory args are set).
 601
 602        Args:
 603            args: a sequence of values that were used to instantiate a Func expression. This is used
 604                to check that the provided arguments don't exceed the function argument limit.
 605
 606        Returns:
 607            A list of error messages for all possible errors that were found.
 608        """
 609        errors: t.List[str] = []
 610
 611        for k in self.args:
 612            if k not in self.arg_types:
 613                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 614        for k, mandatory in self.arg_types.items():
 615            v = self.args.get(k)
 616            if mandatory and (v is None or (isinstance(v, list) and not v)):
 617                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 618
 619        if (
 620            args
 621            and isinstance(self, Func)
 622            and len(args) > len(self.arg_types)
 623            and not self.is_var_len_args
 624        ):
 625            errors.append(
 626                f"The number of provided arguments ({len(args)}) is greater than "
 627                f"the maximum number of supported arguments ({len(self.arg_types)})"
 628            )
 629
 630        return errors
 631
 632    def dump(self):
 633        """
 634        Dump this Expression to a JSON-serializable dict.
 635        """
 636        from sqlglot.serde import dump
 637
 638        return dump(self)
 639
 640    @classmethod
 641    def load(cls, obj):
 642        """
 643        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 644        """
 645        from sqlglot.serde import load
 646
 647        return load(obj)
 648
 649
 650IntoType = t.Union[
 651    str,
 652    t.Type[Expression],
 653    t.Collection[t.Union[str, t.Type[Expression]]],
 654]
 655ExpOrStr = t.Union[str, Expression]
 656
 657
 658class Condition(Expression):
 659    def and_(self, *expressions, dialect=None, copy=True, **opts):
 660        """
 661        AND this condition with one or multiple expressions.
 662
 663        Example:
 664            >>> condition("x=1").and_("y=1").sql()
 665            'x = 1 AND y = 1'
 666
 667        Args:
 668            *expressions (str | Expression): the SQL code strings to parse.
 669                If an `Expression` instance is passed, it will be used as-is.
 670            dialect (str): the dialect used to parse the input expression.
 671            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 672            opts (kwargs): other options to use to parse the input expressions.
 673
 674        Returns:
 675            And: the new condition.
 676        """
 677        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 678
 679    def or_(self, *expressions, dialect=None, copy=True, **opts):
 680        """
 681        OR this condition with one or multiple expressions.
 682
 683        Example:
 684            >>> condition("x=1").or_("y=1").sql()
 685            'x = 1 OR y = 1'
 686
 687        Args:
 688            *expressions (str | Expression): the SQL code strings to parse.
 689                If an `Expression` instance is passed, it will be used as-is.
 690            dialect (str): the dialect used to parse the input expression.
 691            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
 692            opts (kwargs): other options to use to parse the input expressions.
 693
 694        Returns:
 695            Or: the new condition.
 696        """
 697        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 698
 699    def not_(self, copy=True):
 700        """
 701        Wrap this condition with NOT.
 702
 703        Example:
 704            >>> condition("x=1").not_().sql()
 705            'NOT x = 1'
 706
 707        Args:
 708            copy (bool): whether or not to copy this object.
 709
 710        Returns:
 711            Not: the new condition.
 712        """
 713        return not_(self, copy=copy)
 714
 715    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 716        this = self.copy()
 717        other = convert(other, copy=True)
 718        if not isinstance(this, klass) and not isinstance(other, klass):
 719            this = _wrap(this, Binary)
 720            other = _wrap(other, Binary)
 721        if reverse:
 722            return klass(this=other, expression=this)
 723        return klass(this=this, expression=other)
 724
 725    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 726        return Bracket(
 727            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 728        )
 729
 730    def isin(
 731        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
 732    ) -> In:
 733        return In(
 734            this=_maybe_copy(self, copy),
 735            expressions=[convert(e, copy=copy) for e in expressions],
 736            query=maybe_parse(query, copy=copy, **opts) if query else None,
 737        )
 738
 739    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
 740        return Between(
 741            this=_maybe_copy(self, copy),
 742            low=convert(low, copy=copy, **opts),
 743            high=convert(high, copy=copy, **opts),
 744        )
 745
 746    def like(self, other: ExpOrStr) -> Like:
 747        return self._binop(Like, other)
 748
 749    def ilike(self, other: ExpOrStr) -> ILike:
 750        return self._binop(ILike, other)
 751
 752    def eq(self, other: t.Any) -> EQ:
 753        return self._binop(EQ, other)
 754
 755    def neq(self, other: t.Any) -> NEQ:
 756        return self._binop(NEQ, other)
 757
 758    def rlike(self, other: ExpOrStr) -> RegexpLike:
 759        return self._binop(RegexpLike, other)
 760
 761    def __lt__(self, other: t.Any) -> LT:
 762        return self._binop(LT, other)
 763
 764    def __le__(self, other: t.Any) -> LTE:
 765        return self._binop(LTE, other)
 766
 767    def __gt__(self, other: t.Any) -> GT:
 768        return self._binop(GT, other)
 769
 770    def __ge__(self, other: t.Any) -> GTE:
 771        return self._binop(GTE, other)
 772
 773    def __add__(self, other: t.Any) -> Add:
 774        return self._binop(Add, other)
 775
 776    def __radd__(self, other: t.Any) -> Add:
 777        return self._binop(Add, other, reverse=True)
 778
 779    def __sub__(self, other: t.Any) -> Sub:
 780        return self._binop(Sub, other)
 781
 782    def __rsub__(self, other: t.Any) -> Sub:
 783        return self._binop(Sub, other, reverse=True)
 784
 785    def __mul__(self, other: t.Any) -> Mul:
 786        return self._binop(Mul, other)
 787
 788    def __rmul__(self, other: t.Any) -> Mul:
 789        return self._binop(Mul, other, reverse=True)
 790
 791    def __truediv__(self, other: t.Any) -> Div:
 792        return self._binop(Div, other)
 793
 794    def __rtruediv__(self, other: t.Any) -> Div:
 795        return self._binop(Div, other, reverse=True)
 796
 797    def __floordiv__(self, other: t.Any) -> IntDiv:
 798        return self._binop(IntDiv, other)
 799
 800    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 801        return self._binop(IntDiv, other, reverse=True)
 802
 803    def __mod__(self, other: t.Any) -> Mod:
 804        return self._binop(Mod, other)
 805
 806    def __rmod__(self, other: t.Any) -> Mod:
 807        return self._binop(Mod, other, reverse=True)
 808
 809    def __pow__(self, other: t.Any) -> Pow:
 810        return self._binop(Pow, other)
 811
 812    def __rpow__(self, other: t.Any) -> Pow:
 813        return self._binop(Pow, other, reverse=True)
 814
 815    def __and__(self, other: t.Any) -> And:
 816        return self._binop(And, other)
 817
 818    def __rand__(self, other: t.Any) -> And:
 819        return self._binop(And, other, reverse=True)
 820
 821    def __or__(self, other: t.Any) -> Or:
 822        return self._binop(Or, other)
 823
 824    def __ror__(self, other: t.Any) -> Or:
 825        return self._binop(Or, other, reverse=True)
 826
 827    def __neg__(self) -> Neg:
 828        return Neg(this=_wrap(self.copy(), Binary))
 829
 830    def __invert__(self) -> Not:
 831        return not_(self.copy())
 832
 833
 834class Predicate(Condition):
 835    """Relationships like x = y, x > 1, x >= y."""
 836
 837
 838class DerivedTable(Expression):
 839    @property
 840    def alias_column_names(self):
 841        table_alias = self.args.get("alias")
 842        if not table_alias:
 843            return []
 844        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 845        return [c.name for c in column_list]
 846
 847    @property
 848    def selects(self):
 849        return self.this.selects if isinstance(self.this, Subqueryable) else []
 850
 851    @property
 852    def named_selects(self):
 853        return [select.output_name for select in self.selects]
 854
 855
 856class Unionable(Expression):
 857    def union(self, expression, distinct=True, dialect=None, **opts):
 858        """
 859        Builds a UNION expression.
 860
 861        Example:
 862            >>> import sqlglot
 863            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 864            'SELECT * FROM foo UNION SELECT * FROM bla'
 865
 866        Args:
 867            expression (str | Expression): the SQL code string.
 868                If an `Expression` instance is passed, it will be used as-is.
 869            distinct (bool): set the DISTINCT flag if and only if this is true.
 870            dialect (str): the dialect used to parse the input expression.
 871            opts (kwargs): other options to use to parse the input expressions.
 872        Returns:
 873            Union: the Union expression.
 874        """
 875        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 876
 877    def intersect(self, expression, distinct=True, dialect=None, **opts):
 878        """
 879        Builds an INTERSECT expression.
 880
 881        Example:
 882            >>> import sqlglot
 883            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 884            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 885
 886        Args:
 887            expression (str | Expression): the SQL code string.
 888                If an `Expression` instance is passed, it will be used as-is.
 889            distinct (bool): set the DISTINCT flag if and only if this is true.
 890            dialect (str): the dialect used to parse the input expression.
 891            opts (kwargs): other options to use to parse the input expressions.
 892        Returns:
 893            Intersect: the Intersect expression
 894        """
 895        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 896
 897    def except_(self, expression, distinct=True, dialect=None, **opts):
 898        """
 899        Builds an EXCEPT expression.
 900
 901        Example:
 902            >>> import sqlglot
 903            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 904            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 905
 906        Args:
 907            expression (str | Expression): the SQL code string.
 908                If an `Expression` instance is passed, it will be used as-is.
 909            distinct (bool): set the DISTINCT flag if and only if this is true.
 910            dialect (str): the dialect used to parse the input expression.
 911            opts (kwargs): other options to use to parse the input expressions.
 912        Returns:
 913            Except: the Except expression
 914        """
 915        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 916
 917
 918class UDTF(DerivedTable, Unionable):
 919    @property
 920    def selects(self):
 921        alias = self.args.get("alias")
 922        return alias.columns if alias else []
 923
 924
 925class Cache(Expression):
 926    arg_types = {
 927        "with": False,
 928        "this": True,
 929        "lazy": False,
 930        "options": False,
 931        "expression": False,
 932    }
 933
 934
 935class Uncache(Expression):
 936    arg_types = {"this": True, "exists": False}
 937
 938
 939class Create(Expression):
 940    arg_types = {
 941        "with": False,
 942        "this": True,
 943        "kind": True,
 944        "expression": False,
 945        "exists": False,
 946        "properties": False,
 947        "replace": False,
 948        "unique": False,
 949        "indexes": False,
 950        "no_schema_binding": False,
 951        "begin": False,
 952    }
 953
 954
 955class Describe(Expression):
 956    arg_types = {"this": True, "kind": False}
 957
 958
 959class Pragma(Expression):
 960    pass
 961
 962
 963class Set(Expression):
 964    arg_types = {"expressions": False}
 965
 966
 967class SetItem(Expression):
 968    arg_types = {
 969        "this": False,
 970        "expressions": False,
 971        "kind": False,
 972        "collate": False,  # MySQL SET NAMES statement
 973        "global": False,
 974    }
 975
 976
 977class Show(Expression):
 978    arg_types = {
 979        "this": True,
 980        "target": False,
 981        "offset": False,
 982        "limit": False,
 983        "like": False,
 984        "where": False,
 985        "db": False,
 986        "full": False,
 987        "mutex": False,
 988        "query": False,
 989        "channel": False,
 990        "global": False,
 991        "log": False,
 992        "position": False,
 993        "types": False,
 994    }
 995
 996
 997class UserDefinedFunction(Expression):
 998    arg_types = {"this": True, "expressions": False, "wrapped": False}
 999
1000
1001class CharacterSet(Expression):
1002    arg_types = {"this": True, "default": False}
1003
1004
1005class With(Expression):
1006    arg_types = {"expressions": True, "recursive": False}
1007
1008    @property
1009    def recursive(self) -> bool:
1010        return bool(self.args.get("recursive"))
1011
1012
1013class WithinGroup(Expression):
1014    arg_types = {"this": True, "expression": False}
1015
1016
1017class CTE(DerivedTable):
1018    arg_types = {"this": True, "alias": True}
1019
1020
1021class TableAlias(Expression):
1022    arg_types = {"this": False, "columns": False}
1023
1024    @property
1025    def columns(self):
1026        return self.args.get("columns") or []
1027
1028
1029class BitString(Condition):
1030    pass
1031
1032
1033class HexString(Condition):
1034    pass
1035
1036
1037class ByteString(Condition):
1038    pass
1039
1040
1041class Column(Condition):
1042    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1043
1044    @property
1045    def table(self) -> str:
1046        return self.text("table")
1047
1048    @property
1049    def db(self) -> str:
1050        return self.text("db")
1051
1052    @property
1053    def catalog(self) -> str:
1054        return self.text("catalog")
1055
1056    @property
1057    def output_name(self) -> str:
1058        return self.name
1059
1060    @property
1061    def parts(self) -> t.List[Identifier]:
1062        """Return the parts of a column in order catalog, db, table, name."""
1063        return [
1064            t.cast(Identifier, self.args[part])
1065            for part in ("catalog", "db", "table", "this")
1066            if self.args.get(part)
1067        ]
1068
1069    def to_dot(self) -> Dot:
1070        """Converts the column into a dot expression."""
1071        parts = self.parts
1072        parent = self.parent
1073
1074        while parent:
1075            if isinstance(parent, Dot):
1076                parts.append(parent.expression)
1077            parent = parent.parent
1078
1079        return Dot.build(parts)
1080
1081
1082class ColumnPosition(Expression):
1083    arg_types = {"this": False, "position": True}
1084
1085
1086class ColumnDef(Expression):
1087    arg_types = {
1088        "this": True,
1089        "kind": False,
1090        "constraints": False,
1091        "exists": False,
1092        "position": False,
1093    }
1094
1095    @property
1096    def constraints(self) -> t.List[ColumnConstraint]:
1097        return self.args.get("constraints") or []
1098
1099
1100class AlterColumn(Expression):
1101    arg_types = {
1102        "this": True,
1103        "dtype": False,
1104        "collate": False,
1105        "using": False,
1106        "default": False,
1107        "drop": False,
1108    }
1109
1110
1111class RenameTable(Expression):
1112    pass
1113
1114
1115class SetTag(Expression):
1116    arg_types = {"expressions": True, "unset": False}
1117
1118
1119class Comment(Expression):
1120    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1121
1122
1123# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1124class MergeTreeTTLAction(Expression):
1125    arg_types = {
1126        "this": True,
1127        "delete": False,
1128        "recompress": False,
1129        "to_disk": False,
1130        "to_volume": False,
1131    }
1132
1133
1134# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1135class MergeTreeTTL(Expression):
1136    arg_types = {
1137        "expressions": True,
1138        "where": False,
1139        "group": False,
1140        "aggregates": False,
1141    }
1142
1143
1144class ColumnConstraint(Expression):
1145    arg_types = {"this": False, "kind": True}
1146
1147    @property
1148    def kind(self) -> ColumnConstraintKind:
1149        return self.args["kind"]
1150
1151
1152class ColumnConstraintKind(Expression):
1153    pass
1154
1155
1156class AutoIncrementColumnConstraint(ColumnConstraintKind):
1157    pass
1158
1159
1160class CaseSpecificColumnConstraint(ColumnConstraintKind):
1161    arg_types = {"not_": True}
1162
1163
1164class CharacterSetColumnConstraint(ColumnConstraintKind):
1165    arg_types = {"this": True}
1166
1167
1168class CheckColumnConstraint(ColumnConstraintKind):
1169    pass
1170
1171
1172class CollateColumnConstraint(ColumnConstraintKind):
1173    pass
1174
1175
1176class CommentColumnConstraint(ColumnConstraintKind):
1177    pass
1178
1179
1180class CompressColumnConstraint(ColumnConstraintKind):
1181    pass
1182
1183
1184class DateFormatColumnConstraint(ColumnConstraintKind):
1185    arg_types = {"this": True}
1186
1187
1188class DefaultColumnConstraint(ColumnConstraintKind):
1189    pass
1190
1191
1192class EncodeColumnConstraint(ColumnConstraintKind):
1193    pass
1194
1195
1196class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1197    # this: True -> ALWAYS, this: False -> BY DEFAULT
1198    arg_types = {
1199        "this": False,
1200        "on_null": False,
1201        "start": False,
1202        "increment": False,
1203        "minvalue": False,
1204        "maxvalue": False,
1205        "cycle": False,
1206    }
1207
1208
1209class InlineLengthColumnConstraint(ColumnConstraintKind):
1210    pass
1211
1212
1213class NotNullColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"allow_null": False}
1215
1216
1217# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1218class OnUpdateColumnConstraint(ColumnConstraintKind):
1219    pass
1220
1221
1222class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1223    arg_types = {"desc": False}
1224
1225
1226class TitleColumnConstraint(ColumnConstraintKind):
1227    pass
1228
1229
1230class UniqueColumnConstraint(ColumnConstraintKind):
1231    arg_types: t.Dict[str, t.Any] = {}
1232
1233
1234class UppercaseColumnConstraint(ColumnConstraintKind):
1235    arg_types: t.Dict[str, t.Any] = {}
1236
1237
1238class PathColumnConstraint(ColumnConstraintKind):
1239    pass
1240
1241
1242class Constraint(Expression):
1243    arg_types = {"this": True, "expressions": True}
1244
1245
1246class Delete(Expression):
1247    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1248
1249    def delete(
1250        self,
1251        table: ExpOrStr,
1252        dialect: DialectType = None,
1253        copy: bool = True,
1254        **opts,
1255    ) -> Delete:
1256        """
1257        Create a DELETE expression or replace the table on an existing DELETE expression.
1258
1259        Example:
1260            >>> delete("tbl").sql()
1261            'DELETE FROM tbl'
1262
1263        Args:
1264            table: the table from which to delete.
1265            dialect: the dialect used to parse the input expression.
1266            copy: if `False`, modify this expression instance in-place.
1267            opts: other options to use to parse the input expressions.
1268
1269        Returns:
1270            Delete: the modified expression.
1271        """
1272        return _apply_builder(
1273            expression=table,
1274            instance=self,
1275            arg="this",
1276            dialect=dialect,
1277            into=Table,
1278            copy=copy,
1279            **opts,
1280        )
1281
1282    def where(
1283        self,
1284        *expressions: ExpOrStr,
1285        append: bool = True,
1286        dialect: DialectType = None,
1287        copy: bool = True,
1288        **opts,
1289    ) -> Delete:
1290        """
1291        Append to or set the WHERE expressions.
1292
1293        Example:
1294            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1295            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1296
1297        Args:
1298            *expressions: the SQL code strings to parse.
1299                If an `Expression` instance is passed, it will be used as-is.
1300                Multiple expressions are combined with an AND operator.
1301            append: if `True`, AND the new expressions to any existing expression.
1302                Otherwise, this resets the expression.
1303            dialect: the dialect used to parse the input expressions.
1304            copy: if `False`, modify this expression instance in-place.
1305            opts: other options to use to parse the input expressions.
1306
1307        Returns:
1308            Delete: the modified expression.
1309        """
1310        return _apply_conjunction_builder(
1311            *expressions,
1312            instance=self,
1313            arg="where",
1314            append=append,
1315            into=Where,
1316            dialect=dialect,
1317            copy=copy,
1318            **opts,
1319        )
1320
1321    def returning(
1322        self,
1323        expression: ExpOrStr,
1324        dialect: DialectType = None,
1325        copy: bool = True,
1326        **opts,
1327    ) -> Delete:
1328        """
1329        Set the RETURNING expression. Not supported by all dialects.
1330
1331        Example:
1332            >>> delete("tbl").returning("*", dialect="postgres").sql()
1333            'DELETE FROM tbl RETURNING *'
1334
1335        Args:
1336            expression: the SQL code strings to parse.
1337                If an `Expression` instance is passed, it will be used as-is.
1338            dialect: the dialect used to parse the input expressions.
1339            copy: if `False`, modify this expression instance in-place.
1340            opts: other options to use to parse the input expressions.
1341
1342        Returns:
1343            Delete: the modified expression.
1344        """
1345        return _apply_builder(
1346            expression=expression,
1347            instance=self,
1348            arg="returning",
1349            prefix="RETURNING",
1350            dialect=dialect,
1351            copy=copy,
1352            into=Returning,
1353            **opts,
1354        )
1355
1356
1357class Drop(Expression):
1358    arg_types = {
1359        "this": False,
1360        "kind": False,
1361        "exists": False,
1362        "temporary": False,
1363        "materialized": False,
1364        "cascade": False,
1365        "constraints": False,
1366        "purge": False,
1367    }
1368
1369
1370class Filter(Expression):
1371    arg_types = {"this": True, "expression": True}
1372
1373
1374class Check(Expression):
1375    pass
1376
1377
1378class Directory(Expression):
1379    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1380    arg_types = {"this": True, "local": False, "row_format": False}
1381
1382
1383class ForeignKey(Expression):
1384    arg_types = {
1385        "expressions": True,
1386        "reference": False,
1387        "delete": False,
1388        "update": False,
1389    }
1390
1391
1392class PrimaryKey(Expression):
1393    arg_types = {"expressions": True, "options": False}
1394
1395
1396class Unique(Expression):
1397    arg_types = {"expressions": True}
1398
1399
1400# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1401# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1402class Into(Expression):
1403    arg_types = {"this": True, "temporary": False, "unlogged": False}
1404
1405
1406class From(Expression):
1407    @property
1408    def name(self) -> str:
1409        return self.this.name
1410
1411    @property
1412    def alias_or_name(self) -> str:
1413        return self.this.alias_or_name
1414
1415
1416class Having(Expression):
1417    pass
1418
1419
1420class Hint(Expression):
1421    arg_types = {"expressions": True}
1422
1423
1424class JoinHint(Expression):
1425    arg_types = {"this": True, "expressions": True}
1426
1427
1428class Identifier(Expression):
1429    arg_types = {"this": True, "quoted": False}
1430
1431    @property
1432    def quoted(self):
1433        return bool(self.args.get("quoted"))
1434
1435    @property
1436    def hashable_args(self) -> t.Any:
1437        if self.quoted and any(char.isupper() for char in self.this):
1438            return (self.this, self.quoted)
1439        return self.this.lower()
1440
1441    @property
1442    def output_name(self):
1443        return self.name
1444
1445
1446class Index(Expression):
1447    arg_types = {
1448        "this": False,
1449        "table": False,
1450        "where": False,
1451        "columns": False,
1452        "unique": False,
1453        "primary": False,
1454        "amp": False,  # teradata
1455    }
1456
1457
1458class Insert(Expression):
1459    arg_types = {
1460        "with": False,
1461        "this": True,
1462        "expression": False,
1463        "conflict": False,
1464        "returning": False,
1465        "overwrite": False,
1466        "exists": False,
1467        "partition": False,
1468        "alternative": False,
1469    }
1470
1471
1472class OnConflict(Expression):
1473    arg_types = {
1474        "duplicate": False,
1475        "expressions": False,
1476        "nothing": False,
1477        "key": False,
1478        "constraint": False,
1479    }
1480
1481
1482class Returning(Expression):
1483    arg_types = {"expressions": True}
1484
1485
1486# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1487class Introducer(Expression):
1488    arg_types = {"this": True, "expression": True}
1489
1490
1491# national char, like n'utf8'
1492class National(Expression):
1493    pass
1494
1495
1496class LoadData(Expression):
1497    arg_types = {
1498        "this": True,
1499        "local": False,
1500        "overwrite": False,
1501        "inpath": True,
1502        "partition": False,
1503        "input_format": False,
1504        "serde": False,
1505    }
1506
1507
1508class Partition(Expression):
1509    arg_types = {"expressions": True}
1510
1511
1512class Fetch(Expression):
1513    arg_types = {
1514        "direction": False,
1515        "count": False,
1516        "percent": False,
1517        "with_ties": False,
1518    }
1519
1520
1521class Group(Expression):
1522    arg_types = {
1523        "expressions": False,
1524        "grouping_sets": False,
1525        "cube": False,
1526        "rollup": False,
1527        "totals": False,
1528    }
1529
1530
1531class Lambda(Expression):
1532    arg_types = {"this": True, "expressions": True}
1533
1534
1535class Limit(Expression):
1536    arg_types = {"this": False, "expression": True}
1537
1538
1539class Literal(Condition):
1540    arg_types = {"this": True, "is_string": True}
1541
1542    @property
1543    def hashable_args(self) -> t.Any:
1544        return (self.this, self.args.get("is_string"))
1545
1546    @classmethod
1547    def number(cls, number) -> Literal:
1548        return cls(this=str(number), is_string=False)
1549
1550    @classmethod
1551    def string(cls, string) -> Literal:
1552        return cls(this=str(string), is_string=True)
1553
1554    @property
1555    def output_name(self):
1556        return self.name
1557
1558
1559class Join(Expression):
1560    arg_types = {
1561        "this": True,
1562        "on": False,
1563        "side": False,
1564        "kind": False,
1565        "using": False,
1566        "natural": False,
1567        "global": False,
1568        "hint": False,
1569    }
1570
1571    @property
1572    def kind(self):
1573        return self.text("kind").upper()
1574
1575    @property
1576    def side(self):
1577        return self.text("side").upper()
1578
1579    @property
1580    def hint(self):
1581        return self.text("hint").upper()
1582
1583    @property
1584    def alias_or_name(self):
1585        return self.this.alias_or_name
1586
1587    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1588        """
1589        Append to or set the ON expressions.
1590
1591        Example:
1592            >>> import sqlglot
1593            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1594            'JOIN x ON y = 1'
1595
1596        Args:
1597            *expressions (str | Expression): the SQL code strings to parse.
1598                If an `Expression` instance is passed, it will be used as-is.
1599                Multiple expressions are combined with an AND operator.
1600            append (bool): if `True`, AND the new expressions to any existing expression.
1601                Otherwise, this resets the expression.
1602            dialect (str): the dialect used to parse the input expressions.
1603            copy (bool): if `False`, modify this expression instance in-place.
1604            opts (kwargs): other options to use to parse the input expressions.
1605
1606        Returns:
1607            Join: the modified join expression.
1608        """
1609        join = _apply_conjunction_builder(
1610            *expressions,
1611            instance=self,
1612            arg="on",
1613            append=append,
1614            dialect=dialect,
1615            copy=copy,
1616            **opts,
1617        )
1618
1619        if join.kind == "CROSS":
1620            join.set("kind", None)
1621
1622        return join
1623
1624    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1625        """
1626        Append to or set the USING expressions.
1627
1628        Example:
1629            >>> import sqlglot
1630            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1631            'JOIN x USING (foo, bla)'
1632
1633        Args:
1634            *expressions (str | Expression): the SQL code strings to parse.
1635                If an `Expression` instance is passed, it will be used as-is.
1636            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1637                Otherwise, this resets the expression.
1638            dialect (str): the dialect used to parse the input expressions.
1639            copy (bool): if `False`, modify this expression instance in-place.
1640            opts (kwargs): other options to use to parse the input expressions.
1641
1642        Returns:
1643            Join: the modified join expression.
1644        """
1645        join = _apply_list_builder(
1646            *expressions,
1647            instance=self,
1648            arg="using",
1649            append=append,
1650            dialect=dialect,
1651            copy=copy,
1652            **opts,
1653        )
1654
1655        if join.kind == "CROSS":
1656            join.set("kind", None)
1657
1658        return join
1659
1660
1661class Lateral(UDTF):
1662    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1663
1664
1665class MatchRecognize(Expression):
1666    arg_types = {
1667        "partition_by": False,
1668        "order": False,
1669        "measures": False,
1670        "rows": False,
1671        "after": False,
1672        "pattern": False,
1673        "define": False,
1674        "alias": False,
1675    }
1676
1677
1678# Clickhouse FROM FINAL modifier
1679# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1680class Final(Expression):
1681    pass
1682
1683
1684class Offset(Expression):
1685    arg_types = {"this": False, "expression": True}
1686
1687
1688class Order(Expression):
1689    arg_types = {"this": False, "expressions": True}
1690
1691
1692# hive specific sorts
1693# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1694class Cluster(Order):
1695    pass
1696
1697
1698class Distribute(Order):
1699    pass
1700
1701
1702class Sort(Order):
1703    pass
1704
1705
1706class Ordered(Expression):
1707    arg_types = {"this": True, "desc": True, "nulls_first": True}
1708
1709
1710class Property(Expression):
1711    arg_types = {"this": True, "value": True}
1712
1713
1714class AfterJournalProperty(Property):
1715    arg_types = {"no": True, "dual": False, "local": False}
1716
1717
1718class AlgorithmProperty(Property):
1719    arg_types = {"this": True}
1720
1721
1722class AutoIncrementProperty(Property):
1723    arg_types = {"this": True}
1724
1725
1726class BlockCompressionProperty(Property):
1727    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1728
1729
1730class CharacterSetProperty(Property):
1731    arg_types = {"this": True, "default": True}
1732
1733
1734class ChecksumProperty(Property):
1735    arg_types = {"on": False, "default": False}
1736
1737
1738class CollateProperty(Property):
1739    arg_types = {"this": True}
1740
1741
1742class DataBlocksizeProperty(Property):
1743    arg_types = {"size": False, "units": False, "min": False, "default": False}
1744
1745
1746class DefinerProperty(Property):
1747    arg_types = {"this": True}
1748
1749
1750class DistKeyProperty(Property):
1751    arg_types = {"this": True}
1752
1753
1754class DistStyleProperty(Property):
1755    arg_types = {"this": True}
1756
1757
1758class EngineProperty(Property):
1759    arg_types = {"this": True}
1760
1761
1762class ExecuteAsProperty(Property):
1763    arg_types = {"this": True}
1764
1765
1766class ExternalProperty(Property):
1767    arg_types = {"this": False}
1768
1769
1770class FallbackProperty(Property):
1771    arg_types = {"no": True, "protection": False}
1772
1773
1774class FileFormatProperty(Property):
1775    arg_types = {"this": True}
1776
1777
1778class FreespaceProperty(Property):
1779    arg_types = {"this": True, "percent": False}
1780
1781
1782class InputOutputFormat(Expression):
1783    arg_types = {"input_format": False, "output_format": False}
1784
1785
1786class IsolatedLoadingProperty(Property):
1787    arg_types = {
1788        "no": True,
1789        "concurrent": True,
1790        "for_all": True,
1791        "for_insert": True,
1792        "for_none": True,
1793    }
1794
1795
1796class JournalProperty(Property):
1797    arg_types = {"no": True, "dual": False, "before": False}
1798
1799
1800class LanguageProperty(Property):
1801    arg_types = {"this": True}
1802
1803
1804class LikeProperty(Property):
1805    arg_types = {"this": True, "expressions": False}
1806
1807
1808class LocationProperty(Property):
1809    arg_types = {"this": True}
1810
1811
1812class LockingProperty(Property):
1813    arg_types = {
1814        "this": False,
1815        "kind": True,
1816        "for_or_in": True,
1817        "lock_type": True,
1818        "override": False,
1819    }
1820
1821
1822class LogProperty(Property):
1823    arg_types = {"no": True}
1824
1825
1826class MaterializedProperty(Property):
1827    arg_types = {"this": False}
1828
1829
1830class MergeBlockRatioProperty(Property):
1831    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1832
1833
1834class NoPrimaryIndexProperty(Property):
1835    arg_types = {"this": False}
1836
1837
1838class OnCommitProperty(Property):
1839    arg_type = {"this": False}
1840
1841
1842class PartitionedByProperty(Property):
1843    arg_types = {"this": True}
1844
1845
1846class ReturnsProperty(Property):
1847    arg_types = {"this": True, "is_table": False, "table": False}
1848
1849
1850class RowFormatProperty(Property):
1851    arg_types = {"this": True}
1852
1853
1854class RowFormatDelimitedProperty(Property):
1855    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1856    arg_types = {
1857        "fields": False,
1858        "escaped": False,
1859        "collection_items": False,
1860        "map_keys": False,
1861        "lines": False,
1862        "null": False,
1863        "serde": False,
1864    }
1865
1866
1867class RowFormatSerdeProperty(Property):
1868    arg_types = {"this": True}
1869
1870
1871class SchemaCommentProperty(Property):
1872    arg_types = {"this": True}
1873
1874
1875class SerdeProperties(Property):
1876    arg_types = {"expressions": True}
1877
1878
1879class SetProperty(Property):
1880    arg_types = {"multi": True}
1881
1882
1883class SettingsProperty(Property):
1884    arg_types = {"expressions": True}
1885
1886
1887class SortKeyProperty(Property):
1888    arg_types = {"this": True, "compound": False}
1889
1890
1891class SqlSecurityProperty(Property):
1892    arg_types = {"definer": True}
1893
1894
1895class StabilityProperty(Property):
1896    arg_types = {"this": True}
1897
1898
1899class TableFormatProperty(Property):
1900    arg_types = {"this": True}
1901
1902
1903class TemporaryProperty(Property):
1904    arg_types = {"global_": True}
1905
1906
1907class TransientProperty(Property):
1908    arg_types = {"this": False}
1909
1910
1911class VolatileProperty(Property):
1912    arg_types = {"this": False}
1913
1914
1915class WithDataProperty(Property):
1916    arg_types = {"no": True, "statistics": False}
1917
1918
1919class WithJournalTableProperty(Property):
1920    arg_types = {"this": True}
1921
1922
1923class Properties(Expression):
1924    arg_types = {"expressions": True}
1925
1926    NAME_TO_PROPERTY = {
1927        "ALGORITHM": AlgorithmProperty,
1928        "AUTO_INCREMENT": AutoIncrementProperty,
1929        "CHARACTER SET": CharacterSetProperty,
1930        "COLLATE": CollateProperty,
1931        "COMMENT": SchemaCommentProperty,
1932        "DEFINER": DefinerProperty,
1933        "DISTKEY": DistKeyProperty,
1934        "DISTSTYLE": DistStyleProperty,
1935        "ENGINE": EngineProperty,
1936        "EXECUTE AS": ExecuteAsProperty,
1937        "FORMAT": FileFormatProperty,
1938        "LANGUAGE": LanguageProperty,
1939        "LOCATION": LocationProperty,
1940        "PARTITIONED_BY": PartitionedByProperty,
1941        "RETURNS": ReturnsProperty,
1942        "ROW_FORMAT": RowFormatProperty,
1943        "SORTKEY": SortKeyProperty,
1944        "TABLE_FORMAT": TableFormatProperty,
1945    }
1946
1947    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1948
1949    # CREATE property locations
1950    # Form: schema specified
1951    #   create [POST_CREATE]
1952    #     table a [POST_NAME]
1953    #     (b int) [POST_SCHEMA]
1954    #     with ([POST_WITH])
1955    #     index (b) [POST_INDEX]
1956    #
1957    # Form: alias selection
1958    #   create [POST_CREATE]
1959    #     table a [POST_NAME]
1960    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1961    #     index (c) [POST_INDEX]
1962    class Location(AutoName):
1963        POST_CREATE = auto()
1964        POST_NAME = auto()
1965        POST_SCHEMA = auto()
1966        POST_WITH = auto()
1967        POST_ALIAS = auto()
1968        POST_EXPRESSION = auto()
1969        POST_INDEX = auto()
1970        UNSUPPORTED = auto()
1971
1972    @classmethod
1973    def from_dict(cls, properties_dict) -> Properties:
1974        expressions = []
1975        for key, value in properties_dict.items():
1976            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1977            if property_cls:
1978                expressions.append(property_cls(this=convert(value)))
1979            else:
1980                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1981
1982        return cls(expressions=expressions)
1983
1984
1985class Qualify(Expression):
1986    pass
1987
1988
1989# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1990class Return(Expression):
1991    pass
1992
1993
1994class Reference(Expression):
1995    arg_types = {"this": True, "expressions": False, "options": False}
1996
1997
1998class Tuple(Expression):
1999    arg_types = {"expressions": False}
2000
2001    def isin(
2002        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2003    ) -> In:
2004        return In(
2005            this=_maybe_copy(self, copy),
2006            expressions=[convert(e, copy=copy) for e in expressions],
2007            query=maybe_parse(query, copy=copy, **opts) if query else None,
2008        )
2009
2010
2011class Subqueryable(Unionable):
2012    def subquery(self, alias=None, copy=True) -> Subquery:
2013        """
2014        Convert this expression to an aliased expression that can be used as a Subquery.
2015
2016        Example:
2017            >>> subquery = Select().select("x").from_("tbl").subquery()
2018            >>> Select().select("x").from_(subquery).sql()
2019            'SELECT x FROM (SELECT x FROM tbl)'
2020
2021        Args:
2022            alias (str | Identifier): an optional alias for the subquery
2023            copy (bool): if `False`, modify this expression instance in-place.
2024
2025        Returns:
2026            Alias: the subquery
2027        """
2028        instance = _maybe_copy(self, copy)
2029        return Subquery(
2030            this=instance,
2031            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2032        )
2033
2034    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2035        raise NotImplementedError
2036
2037    @property
2038    def ctes(self):
2039        with_ = self.args.get("with")
2040        if not with_:
2041            return []
2042        return with_.expressions
2043
2044    @property
2045    def selects(self):
2046        raise NotImplementedError("Subqueryable objects must implement `selects`")
2047
2048    @property
2049    def named_selects(self):
2050        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2051
2052    def with_(
2053        self,
2054        alias,
2055        as_,
2056        recursive=None,
2057        append=True,
2058        dialect=None,
2059        copy=True,
2060        **opts,
2061    ):
2062        """
2063        Append to or set the common table expressions.
2064
2065        Example:
2066            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2067            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2068
2069        Args:
2070            alias (str | Expression): the SQL code string to parse as the table name.
2071                If an `Expression` instance is passed, this is used as-is.
2072            as_ (str | Expression): the SQL code string to parse as the table expression.
2073                If an `Expression` instance is passed, it will be used as-is.
2074            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2075            append (bool): if `True`, add to any existing expressions.
2076                Otherwise, this resets the expressions.
2077            dialect (str): the dialect used to parse the input expression.
2078            copy (bool): if `False`, modify this expression instance in-place.
2079            opts (kwargs): other options to use to parse the input expressions.
2080
2081        Returns:
2082            Select: the modified expression.
2083        """
2084        alias_expression = maybe_parse(
2085            alias,
2086            dialect=dialect,
2087            into=TableAlias,
2088            **opts,
2089        )
2090        as_expression = maybe_parse(
2091            as_,
2092            dialect=dialect,
2093            **opts,
2094        )
2095        cte = CTE(
2096            this=as_expression,
2097            alias=alias_expression,
2098        )
2099        return _apply_child_list_builder(
2100            cte,
2101            instance=self,
2102            arg="with",
2103            append=append,
2104            copy=copy,
2105            into=With,
2106            properties={"recursive": recursive or False},
2107        )
2108
2109
2110QUERY_MODIFIERS = {
2111    "match": False,
2112    "laterals": False,
2113    "joins": False,
2114    "pivots": False,
2115    "where": False,
2116    "group": False,
2117    "having": False,
2118    "qualify": False,
2119    "windows": False,
2120    "distribute": False,
2121    "sort": False,
2122    "cluster": False,
2123    "order": False,
2124    "limit": False,
2125    "offset": False,
2126    "lock": False,
2127    "sample": False,
2128    "settings": False,
2129    "format": False,
2130}
2131
2132
2133class Table(Expression):
2134    arg_types = {
2135        "this": True,
2136        "alias": False,
2137        "db": False,
2138        "catalog": False,
2139        "laterals": False,
2140        "joins": False,
2141        "pivots": False,
2142        "hints": False,
2143        "system_time": False,
2144    }
2145
2146    @property
2147    def db(self) -> str:
2148        return self.text("db")
2149
2150    @property
2151    def catalog(self) -> str:
2152        return self.text("catalog")
2153
2154    @property
2155    def parts(self) -> t.List[Identifier]:
2156        """Return the parts of a column in order catalog, db, table."""
2157        return [
2158            t.cast(Identifier, self.args[part])
2159            for part in ("catalog", "db", "this")
2160            if self.args.get(part)
2161        ]
2162
2163
2164# See the TSQL "Querying data in a system-versioned temporal table" page
2165class SystemTime(Expression):
2166    arg_types = {
2167        "this": False,
2168        "expression": False,
2169        "kind": True,
2170    }
2171
2172
2173class Union(Subqueryable):
2174    arg_types = {
2175        "with": False,
2176        "this": True,
2177        "expression": True,
2178        "distinct": False,
2179        **QUERY_MODIFIERS,
2180    }
2181
2182    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2183        """
2184        Set the LIMIT expression.
2185
2186        Example:
2187            >>> select("1").union(select("1")).limit(1).sql()
2188            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2189
2190        Args:
2191            expression (str | int | Expression): the SQL code string to parse.
2192                This can also be an integer.
2193                If a `Limit` instance is passed, this is used as-is.
2194                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2195            dialect (str): the dialect used to parse the input expression.
2196            copy (bool): if `False`, modify this expression instance in-place.
2197            opts (kwargs): other options to use to parse the input expressions.
2198
2199        Returns:
2200            Select: The limited subqueryable.
2201        """
2202        return (
2203            select("*")
2204            .from_(self.subquery(alias="_l_0", copy=copy))
2205            .limit(expression, dialect=dialect, copy=False, **opts)
2206        )
2207
2208    def select(
2209        self,
2210        *expressions: ExpOrStr,
2211        append: bool = True,
2212        dialect: DialectType = None,
2213        copy: bool = True,
2214        **opts,
2215    ) -> Union:
2216        """Append to or set the SELECT of the union recursively.
2217
2218        Example:
2219            >>> from sqlglot import parse_one
2220            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2221            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2222
2223        Args:
2224            *expressions: the SQL code strings to parse.
2225                If an `Expression` instance is passed, it will be used as-is.
2226            append: if `True`, add to any existing expressions.
2227                Otherwise, this resets the expressions.
2228            dialect: the dialect used to parse the input expressions.
2229            copy: if `False`, modify this expression instance in-place.
2230            opts: other options to use to parse the input expressions.
2231
2232        Returns:
2233            Union: the modified expression.
2234        """
2235        this = self.copy() if copy else self
2236        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2237        this.expression.unnest().select(
2238            *expressions, append=append, dialect=dialect, copy=False, **opts
2239        )
2240        return this
2241
2242    @property
2243    def named_selects(self):
2244        return self.this.unnest().named_selects
2245
2246    @property
2247    def is_star(self) -> bool:
2248        return self.this.is_star or self.expression.is_star
2249
2250    @property
2251    def selects(self):
2252        return self.this.unnest().selects
2253
2254    @property
2255    def left(self):
2256        return self.this
2257
2258    @property
2259    def right(self):
2260        return self.expression
2261
2262
2263class Except(Union):
2264    pass
2265
2266
2267class Intersect(Union):
2268    pass
2269
2270
2271class Unnest(UDTF):
2272    arg_types = {
2273        "expressions": True,
2274        "ordinality": False,
2275        "alias": False,
2276        "offset": False,
2277    }
2278
2279
2280class Update(Expression):
2281    arg_types = {
2282        "with": False,
2283        "this": False,
2284        "expressions": True,
2285        "from": False,
2286        "where": False,
2287        "returning": False,
2288    }
2289
2290
2291class Values(UDTF):
2292    arg_types = {
2293        "expressions": True,
2294        "ordinality": False,
2295        "alias": False,
2296    }
2297
2298
2299class Var(Expression):
2300    pass
2301
2302
2303class Schema(Expression):
2304    arg_types = {"this": False, "expressions": False}
2305
2306
2307# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2308# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2309class Lock(Expression):
2310    arg_types = {"update": True}
2311
2312
2313class Select(Subqueryable):
2314    arg_types = {
2315        "with": False,
2316        "kind": False,
2317        "expressions": False,
2318        "hint": False,
2319        "distinct": False,
2320        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2321        "value": False,
2322        "into": False,
2323        "from": False,
2324        **QUERY_MODIFIERS,
2325    }
2326
2327    def from_(
2328        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2329    ) -> Select:
2330        """
2331        Set the FROM expression.
2332
2333        Example:
2334            >>> Select().from_("tbl").select("x").sql()
2335            'SELECT x FROM tbl'
2336
2337        Args:
2338            expression : the SQL code strings to parse.
2339                If a `From` instance is passed, this is used as-is.
2340                If another `Expression` instance is passed, it will be wrapped in a `From`.
2341            dialect: the dialect used to parse the input expression.
2342            copy: if `False`, modify this expression instance in-place.
2343            opts: other options to use to parse the input expressions.
2344
2345        Returns:
2346            Select: the modified expression.
2347        """
2348        return _apply_builder(
2349            expression=expression,
2350            instance=self,
2351            arg="from",
2352            into=From,
2353            prefix="FROM",
2354            dialect=dialect,
2355            copy=copy,
2356            **opts,
2357        )
2358
2359    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2360        """
2361        Set the GROUP BY expression.
2362
2363        Example:
2364            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2365            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2366
2367        Args:
2368            *expressions (str | Expression): the SQL code strings to parse.
2369                If a `Group` instance is passed, this is used as-is.
2370                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2371                If nothing is passed in then a group by is not applied to the expression
2372            append (bool): if `True`, add to any existing expressions.
2373                Otherwise, this flattens all the `Group` expression into a single expression.
2374            dialect (str): the dialect used to parse the input expression.
2375            copy (bool): if `False`, modify this expression instance in-place.
2376            opts (kwargs): other options to use to parse the input expressions.
2377
2378        Returns:
2379            Select: the modified expression.
2380        """
2381        if not expressions:
2382            return self if not copy else self.copy()
2383        return _apply_child_list_builder(
2384            *expressions,
2385            instance=self,
2386            arg="group",
2387            append=append,
2388            copy=copy,
2389            prefix="GROUP BY",
2390            into=Group,
2391            dialect=dialect,
2392            **opts,
2393        )
2394
2395    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2396        """
2397        Set the ORDER BY expression.
2398
2399        Example:
2400            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2401            'SELECT x FROM tbl ORDER BY x DESC'
2402
2403        Args:
2404            *expressions (str | Expression): the SQL code strings to parse.
2405                If a `Group` instance is passed, this is used as-is.
2406                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2407            append (bool): if `True`, add to any existing expressions.
2408                Otherwise, this flattens all the `Order` expression into a single expression.
2409            dialect (str): the dialect used to parse the input expression.
2410            copy (bool): if `False`, modify this expression instance in-place.
2411            opts (kwargs): other options to use to parse the input expressions.
2412
2413        Returns:
2414            Select: the modified expression.
2415        """
2416        return _apply_child_list_builder(
2417            *expressions,
2418            instance=self,
2419            arg="order",
2420            append=append,
2421            copy=copy,
2422            prefix="ORDER BY",
2423            into=Order,
2424            dialect=dialect,
2425            **opts,
2426        )
2427
2428    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2429        """
2430        Set the SORT BY expression.
2431
2432        Example:
2433            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2434            'SELECT x FROM tbl SORT BY x DESC'
2435
2436        Args:
2437            *expressions (str | Expression): the SQL code strings to parse.
2438                If a `Group` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2440            append (bool): if `True`, add to any existing expressions.
2441                Otherwise, this flattens all the `Order` expression into a single expression.
2442            dialect (str): the dialect used to parse the input expression.
2443            copy (bool): if `False`, modify this expression instance in-place.
2444            opts (kwargs): other options to use to parse the input expressions.
2445
2446        Returns:
2447            Select: the modified expression.
2448        """
2449        return _apply_child_list_builder(
2450            *expressions,
2451            instance=self,
2452            arg="sort",
2453            append=append,
2454            copy=copy,
2455            prefix="SORT BY",
2456            into=Sort,
2457            dialect=dialect,
2458            **opts,
2459        )
2460
2461    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2462        """
2463        Set the CLUSTER BY expression.
2464
2465        Example:
2466            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2467            'SELECT x FROM tbl CLUSTER BY x DESC'
2468
2469        Args:
2470            *expressions (str | Expression): the SQL code strings to parse.
2471                If a `Group` instance is passed, this is used as-is.
2472                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2473            append (bool): if `True`, add to any existing expressions.
2474                Otherwise, this flattens all the `Order` expression into a single expression.
2475            dialect (str): the dialect used to parse the input expression.
2476            copy (bool): if `False`, modify this expression instance in-place.
2477            opts (kwargs): other options to use to parse the input expressions.
2478
2479        Returns:
2480            Select: the modified expression.
2481        """
2482        return _apply_child_list_builder(
2483            *expressions,
2484            instance=self,
2485            arg="cluster",
2486            append=append,
2487            copy=copy,
2488            prefix="CLUSTER BY",
2489            into=Cluster,
2490            dialect=dialect,
2491            **opts,
2492        )
2493
2494    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2495        """
2496        Set the LIMIT expression.
2497
2498        Example:
2499            >>> Select().from_("tbl").select("x").limit(10).sql()
2500            'SELECT x FROM tbl LIMIT 10'
2501
2502        Args:
2503            expression (str | int | Expression): the SQL code string to parse.
2504                This can also be an integer.
2505                If a `Limit` instance is passed, this is used as-is.
2506                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2507            dialect (str): the dialect used to parse the input expression.
2508            copy (bool): if `False`, modify this expression instance in-place.
2509            opts (kwargs): other options to use to parse the input expressions.
2510
2511        Returns:
2512            Select: the modified expression.
2513        """
2514        return _apply_builder(
2515            expression=expression,
2516            instance=self,
2517            arg="limit",
2518            into=Limit,
2519            prefix="LIMIT",
2520            dialect=dialect,
2521            copy=copy,
2522            **opts,
2523        )
2524
2525    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2526        """
2527        Set the OFFSET expression.
2528
2529        Example:
2530            >>> Select().from_("tbl").select("x").offset(10).sql()
2531            'SELECT x FROM tbl OFFSET 10'
2532
2533        Args:
2534            expression (str | int | Expression): the SQL code string to parse.
2535                This can also be an integer.
2536                If a `Offset` instance is passed, this is used as-is.
2537                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2538            dialect (str): the dialect used to parse the input expression.
2539            copy (bool): if `False`, modify this expression instance in-place.
2540            opts (kwargs): other options to use to parse the input expressions.
2541
2542        Returns:
2543            Select: the modified expression.
2544        """
2545        return _apply_builder(
2546            expression=expression,
2547            instance=self,
2548            arg="offset",
2549            into=Offset,
2550            prefix="OFFSET",
2551            dialect=dialect,
2552            copy=copy,
2553            **opts,
2554        )
2555
2556    def select(
2557        self,
2558        *expressions: ExpOrStr,
2559        append: bool = True,
2560        dialect: DialectType = None,
2561        copy: bool = True,
2562        **opts,
2563    ) -> Select:
2564        """
2565        Append to or set the SELECT expressions.
2566
2567        Example:
2568            >>> Select().select("x", "y").sql()
2569            'SELECT x, y'
2570
2571        Args:
2572            *expressions: the SQL code strings to parse.
2573                If an `Expression` instance is passed, it will be used as-is.
2574            append: if `True`, add to any existing expressions.
2575                Otherwise, this resets the expressions.
2576            dialect: the dialect used to parse the input expressions.
2577            copy: if `False`, modify this expression instance in-place.
2578            opts: other options to use to parse the input expressions.
2579
2580        Returns:
2581            Select: the modified expression.
2582        """
2583        return _apply_list_builder(
2584            *expressions,
2585            instance=self,
2586            arg="expressions",
2587            append=append,
2588            dialect=dialect,
2589            copy=copy,
2590            **opts,
2591        )
2592
2593    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2594        """
2595        Append to or set the LATERAL expressions.
2596
2597        Example:
2598            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2599            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2600
2601        Args:
2602            *expressions (str | Expression): the SQL code strings to parse.
2603                If an `Expression` instance is passed, it will be used as-is.
2604            append (bool): if `True`, add to any existing expressions.
2605                Otherwise, this resets the expressions.
2606            dialect (str): the dialect used to parse the input expressions.
2607            copy (bool): if `False`, modify this expression instance in-place.
2608            opts (kwargs): other options to use to parse the input expressions.
2609
2610        Returns:
2611            Select: the modified expression.
2612        """
2613        return _apply_list_builder(
2614            *expressions,
2615            instance=self,
2616            arg="laterals",
2617            append=append,
2618            into=Lateral,
2619            prefix="LATERAL VIEW",
2620            dialect=dialect,
2621            copy=copy,
2622            **opts,
2623        )
2624
2625    def join(
2626        self,
2627        expression,
2628        on=None,
2629        using=None,
2630        append=True,
2631        join_type=None,
2632        join_alias=None,
2633        dialect=None,
2634        copy=True,
2635        **opts,
2636    ) -> Select:
2637        """
2638        Append to or set the JOIN expressions.
2639
2640        Example:
2641            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2642            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2643
2644            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2645            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2646
2647            Use `join_type` to change the type of join:
2648
2649            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2650            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2651
2652        Args:
2653            expression (str | Expression): the SQL code string to parse.
2654                If an `Expression` instance is passed, it will be used as-is.
2655            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2656                If an `Expression` instance is passed, it will be used as-is.
2657            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2658                If an `Expression` instance is passed, it will be used as-is.
2659            append (bool): if `True`, add to any existing expressions.
2660                Otherwise, this resets the expressions.
2661            join_type (str): If set, alter the parsed join type
2662            dialect (str): the dialect used to parse the input expressions.
2663            copy (bool): if `False`, modify this expression instance in-place.
2664            opts (kwargs): other options to use to parse the input expressions.
2665
2666        Returns:
2667            Select: the modified expression.
2668        """
2669        parse_args = {"dialect": dialect, **opts}
2670
2671        try:
2672            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2673        except ParseError:
2674            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2675
2676        join = expression if isinstance(expression, Join) else Join(this=expression)
2677
2678        if isinstance(join.this, Select):
2679            join.this.replace(join.this.subquery())
2680
2681        if join_type:
2682            natural: t.Optional[Token]
2683            side: t.Optional[Token]
2684            kind: t.Optional[Token]
2685
2686            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2687
2688            if natural:
2689                join.set("natural", True)
2690            if side:
2691                join.set("side", side.text)
2692            if kind:
2693                join.set("kind", kind.text)
2694
2695        if on:
2696            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2697            join.set("on", on)
2698
2699        if using:
2700            join = _apply_list_builder(
2701                *ensure_collection(using),
2702                instance=join,
2703                arg="using",
2704                append=append,
2705                copy=copy,
2706                **opts,
2707            )
2708
2709        if join_alias:
2710            join.set("this", alias_(join.this, join_alias, table=True))
2711        return _apply_list_builder(
2712            join,
2713            instance=self,
2714            arg="joins",
2715            append=append,
2716            copy=copy,
2717            **opts,
2718        )
2719
2720    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2721        """
2722        Append to or set the WHERE expressions.
2723
2724        Example:
2725            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2726            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2727
2728        Args:
2729            *expressions (str | Expression): the SQL code strings to parse.
2730                If an `Expression` instance is passed, it will be used as-is.
2731                Multiple expressions are combined with an AND operator.
2732            append (bool): if `True`, AND the new expressions to any existing expression.
2733                Otherwise, this resets the expression.
2734            dialect (str): the dialect used to parse the input expressions.
2735            copy (bool): if `False`, modify this expression instance in-place.
2736            opts (kwargs): other options to use to parse the input expressions.
2737
2738        Returns:
2739            Select: the modified expression.
2740        """
2741        return _apply_conjunction_builder(
2742            *expressions,
2743            instance=self,
2744            arg="where",
2745            append=append,
2746            into=Where,
2747            dialect=dialect,
2748            copy=copy,
2749            **opts,
2750        )
2751
2752    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2753        """
2754        Append to or set the HAVING expressions.
2755
2756        Example:
2757            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2758            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2759
2760        Args:
2761            *expressions (str | Expression): the SQL code strings to parse.
2762                If an `Expression` instance is passed, it will be used as-is.
2763                Multiple expressions are combined with an AND operator.
2764            append (bool): if `True`, AND the new expressions to any existing expression.
2765                Otherwise, this resets the expression.
2766            dialect (str): the dialect used to parse the input expressions.
2767            copy (bool): if `False`, modify this expression instance in-place.
2768            opts (kwargs): other options to use to parse the input expressions.
2769
2770        Returns:
2771            Select: the modified expression.
2772        """
2773        return _apply_conjunction_builder(
2774            *expressions,
2775            instance=self,
2776            arg="having",
2777            append=append,
2778            into=Having,
2779            dialect=dialect,
2780            copy=copy,
2781            **opts,
2782        )
2783
2784    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2785        return _apply_list_builder(
2786            *expressions,
2787            instance=self,
2788            arg="windows",
2789            append=append,
2790            into=Window,
2791            dialect=dialect,
2792            copy=copy,
2793            **opts,
2794        )
2795
2796    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2797        return _apply_conjunction_builder(
2798            *expressions,
2799            instance=self,
2800            arg="qualify",
2801            append=append,
2802            into=Qualify,
2803            dialect=dialect,
2804            copy=copy,
2805            **opts,
2806        )
2807
2808    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2809        """
2810        Set the OFFSET expression.
2811
2812        Example:
2813            >>> Select().from_("tbl").select("x").distinct().sql()
2814            'SELECT DISTINCT x FROM tbl'
2815
2816        Args:
2817            ons: the expressions to distinct on
2818            distinct: whether the Select should be distinct
2819            copy: if `False`, modify this expression instance in-place.
2820
2821        Returns:
2822            Select: the modified expression.
2823        """
2824        instance = _maybe_copy(self, copy)
2825        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2826        instance.set("distinct", Distinct(on=on) if distinct else None)
2827        return instance
2828
2829    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2830        """
2831        Convert this expression to a CREATE TABLE AS statement.
2832
2833        Example:
2834            >>> Select().select("*").from_("tbl").ctas("x").sql()
2835            'CREATE TABLE x AS SELECT * FROM tbl'
2836
2837        Args:
2838            table (str | Expression): the SQL code string to parse as the table name.
2839                If another `Expression` instance is passed, it will be used as-is.
2840            properties (dict): an optional mapping of table properties
2841            dialect (str): the dialect used to parse the input table.
2842            copy (bool): if `False`, modify this expression instance in-place.
2843            opts (kwargs): other options to use to parse the input table.
2844
2845        Returns:
2846            Create: the CREATE TABLE AS expression
2847        """
2848        instance = _maybe_copy(self, copy)
2849        table_expression = maybe_parse(
2850            table,
2851            into=Table,
2852            dialect=dialect,
2853            **opts,
2854        )
2855        properties_expression = None
2856        if properties:
2857            properties_expression = Properties.from_dict(properties)
2858
2859        return Create(
2860            this=table_expression,
2861            kind="table",
2862            expression=instance,
2863            properties=properties_expression,
2864        )
2865
2866    def lock(self, update: bool = True, copy: bool = True) -> Select:
2867        """
2868        Set the locking read mode for this expression.
2869
2870        Examples:
2871            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2872            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2873
2874            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2875            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2876
2877        Args:
2878            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2879            copy: if `False`, modify this expression instance in-place.
2880
2881        Returns:
2882            The modified expression.
2883        """
2884
2885        inst = _maybe_copy(self, copy)
2886        inst.set("lock", Lock(update=update))
2887
2888        return inst
2889
2890    @property
2891    def named_selects(self) -> t.List[str]:
2892        return [e.output_name for e in self.expressions if e.alias_or_name]
2893
2894    @property
2895    def is_star(self) -> bool:
2896        return any(expression.is_star for expression in self.expressions)
2897
2898    @property
2899    def selects(self) -> t.List[Expression]:
2900        return self.expressions
2901
2902
2903class Subquery(DerivedTable, Unionable):
2904    arg_types = {
2905        "this": True,
2906        "alias": False,
2907        "with": False,
2908        **QUERY_MODIFIERS,
2909    }
2910
2911    def unnest(self):
2912        """
2913        Returns the first non subquery.
2914        """
2915        expression = self
2916        while isinstance(expression, Subquery):
2917            expression = expression.this
2918        return expression
2919
2920    @property
2921    def is_star(self) -> bool:
2922        return self.this.is_star
2923
2924    @property
2925    def output_name(self):
2926        return self.alias
2927
2928
2929class TableSample(Expression):
2930    arg_types = {
2931        "this": False,
2932        "method": False,
2933        "bucket_numerator": False,
2934        "bucket_denominator": False,
2935        "bucket_field": False,
2936        "percent": False,
2937        "rows": False,
2938        "size": False,
2939        "seed": False,
2940        "kind": False,
2941    }
2942
2943
2944class Tag(Expression):
2945    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2946
2947    arg_types = {
2948        "this": False,
2949        "prefix": False,
2950        "postfix": False,
2951    }
2952
2953
2954class Pivot(Expression):
2955    arg_types = {
2956        "this": False,
2957        "alias": False,
2958        "expressions": True,
2959        "field": True,
2960        "unpivot": True,
2961        "columns": False,
2962    }
2963
2964
2965class Window(Expression):
2966    arg_types = {
2967        "this": True,
2968        "partition_by": False,
2969        "order": False,
2970        "spec": False,
2971        "alias": False,
2972        "over": False,
2973        "first": False,
2974    }
2975
2976
2977class WindowSpec(Expression):
2978    arg_types = {
2979        "kind": False,
2980        "start": False,
2981        "start_side": False,
2982        "end": False,
2983        "end_side": False,
2984    }
2985
2986
2987class Where(Expression):
2988    pass
2989
2990
2991class Star(Expression):
2992    arg_types = {"except": False, "replace": False}
2993
2994    @property
2995    def name(self) -> str:
2996        return "*"
2997
2998    @property
2999    def output_name(self):
3000        return self.name
3001
3002
3003class Parameter(Expression):
3004    arg_types = {"this": True, "wrapped": False}
3005
3006
3007class SessionParameter(Expression):
3008    arg_types = {"this": True, "kind": False}
3009
3010
3011class Placeholder(Expression):
3012    arg_types = {"this": False}
3013
3014
3015class Null(Condition):
3016    arg_types: t.Dict[str, t.Any] = {}
3017
3018    @property
3019    def name(self) -> str:
3020        return "NULL"
3021
3022
3023class Boolean(Condition):
3024    pass
3025
3026
3027class DataTypeSize(Expression):
3028    arg_types = {"this": True, "expression": False}
3029
3030
3031class DataType(Expression):
3032    arg_types = {
3033        "this": True,
3034        "expressions": False,
3035        "nested": False,
3036        "values": False,
3037        "prefix": False,
3038    }
3039
3040    class Type(AutoName):
3041        CHAR = auto()
3042        NCHAR = auto()
3043        VARCHAR = auto()
3044        NVARCHAR = auto()
3045        TEXT = auto()
3046        MEDIUMTEXT = auto()
3047        LONGTEXT = auto()
3048        MEDIUMBLOB = auto()
3049        LONGBLOB = auto()
3050        BINARY = auto()
3051        VARBINARY = auto()
3052        INT = auto()
3053        UINT = auto()
3054        TINYINT = auto()
3055        UTINYINT = auto()
3056        SMALLINT = auto()
3057        USMALLINT = auto()
3058        BIGINT = auto()
3059        UBIGINT = auto()
3060        INT128 = auto()
3061        UINT128 = auto()
3062        INT256 = auto()
3063        UINT256 = auto()
3064        FLOAT = auto()
3065        DOUBLE = auto()
3066        DECIMAL = auto()
3067        BIGDECIMAL = auto()
3068        BIT = auto()
3069        BOOLEAN = auto()
3070        JSON = auto()
3071        JSONB = auto()
3072        INTERVAL = auto()
3073        TIME = auto()
3074        TIMESTAMP = auto()
3075        TIMESTAMPTZ = auto()
3076        TIMESTAMPLTZ = auto()
3077        DATE = auto()
3078        DATETIME = auto()
3079        DATETIME64 = auto()
3080        ARRAY = auto()
3081        MAP = auto()
3082        UUID = auto()
3083        GEOGRAPHY = auto()
3084        GEOMETRY = auto()
3085        STRUCT = auto()
3086        NULLABLE = auto()
3087        HLLSKETCH = auto()
3088        HSTORE = auto()
3089        SUPER = auto()
3090        SERIAL = auto()
3091        SMALLSERIAL = auto()
3092        BIGSERIAL = auto()
3093        XML = auto()
3094        UNIQUEIDENTIFIER = auto()
3095        MONEY = auto()
3096        SMALLMONEY = auto()
3097        ROWVERSION = auto()
3098        IMAGE = auto()
3099        VARIANT = auto()
3100        OBJECT = auto()
3101        INET = auto()
3102        NULL = auto()
3103        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3104
3105    TEXT_TYPES = {
3106        Type.CHAR,
3107        Type.NCHAR,
3108        Type.VARCHAR,
3109        Type.NVARCHAR,
3110        Type.TEXT,
3111    }
3112
3113    INTEGER_TYPES = {
3114        Type.INT,
3115        Type.TINYINT,
3116        Type.SMALLINT,
3117        Type.BIGINT,
3118        Type.INT128,
3119        Type.INT256,
3120    }
3121
3122    FLOAT_TYPES = {
3123        Type.FLOAT,
3124        Type.DOUBLE,
3125    }
3126
3127    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3128
3129    TEMPORAL_TYPES = {
3130        Type.TIMESTAMP,
3131        Type.TIMESTAMPTZ,
3132        Type.TIMESTAMPLTZ,
3133        Type.DATE,
3134        Type.DATETIME,
3135        Type.DATETIME64,
3136    }
3137
3138    @classmethod
3139    def build(
3140        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3141    ) -> DataType:
3142        from sqlglot import parse_one
3143
3144        if isinstance(dtype, str):
3145            if dtype.upper() in cls.Type.__members__:
3146                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3147            else:
3148                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3149            if data_type_exp is None:
3150                raise ValueError(f"Unparsable data type value: {dtype}")
3151        elif isinstance(dtype, DataType.Type):
3152            data_type_exp = DataType(this=dtype)
3153        elif isinstance(dtype, DataType):
3154            return dtype
3155        else:
3156            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3157        return DataType(**{**data_type_exp.args, **kwargs})
3158
3159    def is_type(self, dtype: DataType.Type) -> bool:
3160        return self.this == dtype
3161
3162
3163# https://www.postgresql.org/docs/15/datatype-pseudo.html
3164class PseudoType(Expression):
3165    pass
3166
3167
3168# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3169class SubqueryPredicate(Predicate):
3170    pass
3171
3172
3173class All(SubqueryPredicate):
3174    pass
3175
3176
3177class Any(SubqueryPredicate):
3178    pass
3179
3180
3181class Exists(SubqueryPredicate):
3182    pass
3183
3184
3185# Commands to interact with the databases or engines. For most of the command
3186# expressions we parse whatever comes after the command's name as a string.
3187class Command(Expression):
3188    arg_types = {"this": True, "expression": False}
3189
3190
3191class Transaction(Expression):
3192    arg_types = {"this": False, "modes": False}
3193
3194
3195class Commit(Expression):
3196    arg_types = {"chain": False}
3197
3198
3199class Rollback(Expression):
3200    arg_types = {"savepoint": False}
3201
3202
3203class AlterTable(Expression):
3204    arg_types = {"this": True, "actions": True, "exists": False}
3205
3206
3207class AddConstraint(Expression):
3208    arg_types = {"this": False, "expression": False, "enforced": False}
3209
3210
3211class DropPartition(Expression):
3212    arg_types = {"expressions": True, "exists": False}
3213
3214
3215# Binary expressions like (ADD a b)
3216class Binary(Condition):
3217    arg_types = {"this": True, "expression": True}
3218
3219    @property
3220    def left(self):
3221        return self.this
3222
3223    @property
3224    def right(self):
3225        return self.expression
3226
3227
3228class Add(Binary):
3229    pass
3230
3231
3232class Connector(Binary):
3233    pass
3234
3235
3236class And(Connector):
3237    pass
3238
3239
3240class Or(Connector):
3241    pass
3242
3243
3244class BitwiseAnd(Binary):
3245    pass
3246
3247
3248class BitwiseLeftShift(Binary):
3249    pass
3250
3251
3252class BitwiseOr(Binary):
3253    pass
3254
3255
3256class BitwiseRightShift(Binary):
3257    pass
3258
3259
3260class BitwiseXor(Binary):
3261    pass
3262
3263
3264class Div(Binary):
3265    pass
3266
3267
3268class Overlaps(Binary):
3269    pass
3270
3271
3272class Dot(Binary):
3273    @property
3274    def name(self) -> str:
3275        return self.expression.name
3276
3277    @classmethod
3278    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3279        """Build a Dot object with a sequence of expressions."""
3280        if len(expressions) < 2:
3281            raise ValueError(f"Dot requires >= 2 expressions.")
3282
3283        a, b, *expressions = expressions
3284        dot = Dot(this=a, expression=b)
3285
3286        for expression in expressions:
3287            dot = Dot(this=dot, expression=expression)
3288
3289        return dot
3290
3291
3292class DPipe(Binary):
3293    pass
3294
3295
3296class EQ(Binary, Predicate):
3297    pass
3298
3299
3300class NullSafeEQ(Binary, Predicate):
3301    pass
3302
3303
3304class NullSafeNEQ(Binary, Predicate):
3305    pass
3306
3307
3308class Distance(Binary):
3309    pass
3310
3311
3312class Escape(Binary):
3313    pass
3314
3315
3316class Glob(Binary, Predicate):
3317    pass
3318
3319
3320class GT(Binary, Predicate):
3321    pass
3322
3323
3324class GTE(Binary, Predicate):
3325    pass
3326
3327
3328class ILike(Binary, Predicate):
3329    pass
3330
3331
3332class ILikeAny(Binary, Predicate):
3333    pass
3334
3335
3336class IntDiv(Binary):
3337    pass
3338
3339
3340class Is(Binary, Predicate):
3341    pass
3342
3343
3344class Kwarg(Binary):
3345    """Kwarg in special functions like func(kwarg => y)."""
3346
3347
3348class Like(Binary, Predicate):
3349    pass
3350
3351
3352class LikeAny(Binary, Predicate):
3353    pass
3354
3355
3356class LT(Binary, Predicate):
3357    pass
3358
3359
3360class LTE(Binary, Predicate):
3361    pass
3362
3363
3364class Mod(Binary):
3365    pass
3366
3367
3368class Mul(Binary):
3369    pass
3370
3371
3372class NEQ(Binary, Predicate):
3373    pass
3374
3375
3376class SimilarTo(Binary, Predicate):
3377    pass
3378
3379
3380class Slice(Binary):
3381    arg_types = {"this": False, "expression": False}
3382
3383
3384class Sub(Binary):
3385    pass
3386
3387
3388class ArrayOverlaps(Binary):
3389    pass
3390
3391
3392# Unary Expressions
3393# (NOT a)
3394class Unary(Condition):
3395    pass
3396
3397
3398class BitwiseNot(Unary):
3399    pass
3400
3401
3402class Not(Unary):
3403    pass
3404
3405
3406class Paren(Unary):
3407    arg_types = {"this": True, "with": False}
3408
3409
3410class Neg(Unary):
3411    pass
3412
3413
3414class Alias(Expression):
3415    arg_types = {"this": True, "alias": False}
3416
3417    @property
3418    def output_name(self):
3419        return self.alias
3420
3421
3422class Aliases(Expression):
3423    arg_types = {"this": True, "expressions": True}
3424
3425    @property
3426    def aliases(self):
3427        return self.expressions
3428
3429
3430class AtTimeZone(Expression):
3431    arg_types = {"this": True, "zone": True}
3432
3433
3434class Between(Predicate):
3435    arg_types = {"this": True, "low": True, "high": True}
3436
3437
3438class Bracket(Condition):
3439    arg_types = {"this": True, "expressions": True}
3440
3441
3442class Distinct(Expression):
3443    arg_types = {"expressions": False, "on": False}
3444
3445
3446class In(Predicate):
3447    arg_types = {
3448        "this": True,
3449        "expressions": False,
3450        "query": False,
3451        "unnest": False,
3452        "field": False,
3453        "is_global": False,
3454    }
3455
3456
3457class TimeUnit(Expression):
3458    """Automatically converts unit arg into a var."""
3459
3460    arg_types = {"unit": False}
3461
3462    def __init__(self, **args):
3463        unit = args.get("unit")
3464        if isinstance(unit, (Column, Literal)):
3465            args["unit"] = Var(this=unit.name)
3466        elif isinstance(unit, Week):
3467            unit.set("this", Var(this=unit.this.name))
3468        super().__init__(**args)
3469
3470
3471class Interval(TimeUnit):
3472    arg_types = {"this": False, "unit": False}
3473
3474
3475class IgnoreNulls(Expression):
3476    pass
3477
3478
3479class RespectNulls(Expression):
3480    pass
3481
3482
3483# Functions
3484class Func(Condition):
3485    """
3486    The base class for all function expressions.
3487
3488    Attributes:
3489        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3490            treated as a variable length argument and the argument's value will be stored as a list.
3491        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3492            for this function expression. These values are used to map this node to a name during parsing
3493            as well as to provide the function's name during SQL string generation. By default the SQL
3494            name is set to the expression's class name transformed to snake case.
3495    """
3496
3497    is_var_len_args = False
3498
3499    @classmethod
3500    def from_arg_list(cls, args):
3501        if cls.is_var_len_args:
3502            all_arg_keys = list(cls.arg_types)
3503            # If this function supports variable length argument treat the last argument as such.
3504            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3505            num_non_var = len(non_var_len_arg_keys)
3506
3507            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3508            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3509        else:
3510            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3511
3512        return cls(**args_dict)
3513
3514    @classmethod
3515    def sql_names(cls):
3516        if cls is Func:
3517            raise NotImplementedError(
3518                "SQL name is only supported by concrete function implementations"
3519            )
3520        if "_sql_names" not in cls.__dict__:
3521            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3522        return cls._sql_names
3523
3524    @classmethod
3525    def sql_name(cls):
3526        return cls.sql_names()[0]
3527
3528    @classmethod
3529    def default_parser_mappings(cls):
3530        return {name: cls.from_arg_list for name in cls.sql_names()}
3531
3532
3533class AggFunc(Func):
3534    pass
3535
3536
3537class ParameterizedAgg(AggFunc):
3538    arg_types = {"this": True, "expressions": True, "params": True}
3539
3540
3541class Abs(Func):
3542    pass
3543
3544
3545class Anonymous(Func):
3546    arg_types = {"this": True, "expressions": False}
3547    is_var_len_args = True
3548
3549
3550# https://docs.snowflake.com/en/sql-reference/functions/hll
3551# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3552class Hll(AggFunc):
3553    arg_types = {"this": True, "expressions": False}
3554    is_var_len_args = True
3555
3556
3557class ApproxDistinct(AggFunc):
3558    arg_types = {"this": True, "accuracy": False}
3559
3560
3561class Array(Func):
3562    arg_types = {"expressions": False}
3563    is_var_len_args = True
3564
3565
3566# https://docs.snowflake.com/en/sql-reference/functions/to_char
3567class ToChar(Func):
3568    arg_types = {"this": True, "format": False}
3569
3570
3571class GenerateSeries(Func):
3572    arg_types = {"start": True, "end": True, "step": False}
3573
3574
3575class ArrayAgg(AggFunc):
3576    pass
3577
3578
3579class ArrayAll(Func):
3580    arg_types = {"this": True, "expression": True}
3581
3582
3583class ArrayAny(Func):
3584    arg_types = {"this": True, "expression": True}
3585
3586
3587class ArrayConcat(Func):
3588    arg_types = {"this": True, "expressions": False}
3589    is_var_len_args = True
3590
3591
3592class ArrayContains(Binary, Func):
3593    pass
3594
3595
3596class ArrayContained(Binary):
3597    pass
3598
3599
3600class ArrayFilter(Func):
3601    arg_types = {"this": True, "expression": True}
3602    _sql_names = ["FILTER", "ARRAY_FILTER"]
3603
3604
3605class ArrayJoin(Func):
3606    arg_types = {"this": True, "expression": True, "null": False}
3607
3608
3609class ArraySize(Func):
3610    arg_types = {"this": True, "expression": False}
3611
3612
3613class ArraySort(Func):
3614    arg_types = {"this": True, "expression": False}
3615
3616
3617class ArraySum(Func):
3618    pass
3619
3620
3621class ArrayUnionAgg(AggFunc):
3622    pass
3623
3624
3625class Avg(AggFunc):
3626    pass
3627
3628
3629class AnyValue(AggFunc):
3630    pass
3631
3632
3633class Case(Func):
3634    arg_types = {"this": False, "ifs": True, "default": False}
3635
3636    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3637        instance = _maybe_copy(self, copy)
3638        instance.append(
3639            "ifs",
3640            If(
3641                this=maybe_parse(condition, copy=copy, **opts),
3642                true=maybe_parse(then, copy=copy, **opts),
3643            ),
3644        )
3645        return instance
3646
3647    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3648        instance = _maybe_copy(self, copy)
3649        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3650        return instance
3651
3652
3653class Cast(Func):
3654    arg_types = {"this": True, "to": True}
3655
3656    @property
3657    def name(self) -> str:
3658        return self.this.name
3659
3660    @property
3661    def to(self):
3662        return self.args["to"]
3663
3664    @property
3665    def output_name(self):
3666        return self.name
3667
3668    def is_type(self, dtype: DataType.Type) -> bool:
3669        return self.to.is_type(dtype)
3670
3671
3672class CastToStrType(Func):
3673    arg_types = {"this": True, "expression": True}
3674
3675
3676class Collate(Binary):
3677    pass
3678
3679
3680class TryCast(Cast):
3681    pass
3682
3683
3684class Ceil(Func):
3685    arg_types = {"this": True, "decimals": False}
3686    _sql_names = ["CEIL", "CEILING"]
3687
3688
3689class Coalesce(Func):
3690    arg_types = {"this": True, "expressions": False}
3691    is_var_len_args = True
3692
3693
3694class Concat(Func):
3695    arg_types = {"expressions": True}
3696    is_var_len_args = True
3697
3698
3699class ConcatWs(Concat):
3700    _sql_names = ["CONCAT_WS"]
3701
3702
3703class Count(AggFunc):
3704    arg_types = {"this": False}
3705
3706
3707class CountIf(AggFunc):
3708    pass
3709
3710
3711class CurrentDate(Func):
3712    arg_types = {"this": False}
3713
3714
3715class CurrentDatetime(Func):
3716    arg_types = {"this": False}
3717
3718
3719class CurrentTime(Func):
3720    arg_types = {"this": False}
3721
3722
3723class CurrentTimestamp(Func):
3724    arg_types = {"this": False}
3725
3726
3727class CurrentUser(Func):
3728    arg_types = {"this": False}
3729
3730
3731class DateAdd(Func, TimeUnit):
3732    arg_types = {"this": True, "expression": True, "unit": False}
3733
3734
3735class DateSub(Func, TimeUnit):
3736    arg_types = {"this": True, "expression": True, "unit": False}
3737
3738
3739class DateDiff(Func, TimeUnit):
3740    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3741    arg_types = {"this": True, "expression": True, "unit": False}
3742
3743
3744class DateTrunc(Func):
3745    arg_types = {"unit": True, "this": True, "zone": False}
3746
3747
3748class DatetimeAdd(Func, TimeUnit):
3749    arg_types = {"this": True, "expression": True, "unit": False}
3750
3751
3752class DatetimeSub(Func, TimeUnit):
3753    arg_types = {"this": True, "expression": True, "unit": False}
3754
3755
3756class DatetimeDiff(Func, TimeUnit):
3757    arg_types = {"this": True, "expression": True, "unit": False}
3758
3759
3760class DatetimeTrunc(Func, TimeUnit):
3761    arg_types = {"this": True, "unit": True, "zone": False}
3762
3763
3764class DayOfWeek(Func):
3765    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3766
3767
3768class DayOfMonth(Func):
3769    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3770
3771
3772class DayOfYear(Func):
3773    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3774
3775
3776class WeekOfYear(Func):
3777    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3778
3779
3780class LastDateOfMonth(Func):
3781    pass
3782
3783
3784class Extract(Func):
3785    arg_types = {"this": True, "expression": True}
3786
3787
3788class TimestampAdd(Func, TimeUnit):
3789    arg_types = {"this": True, "expression": True, "unit": False}
3790
3791
3792class TimestampSub(Func, TimeUnit):
3793    arg_types = {"this": True, "expression": True, "unit": False}
3794
3795
3796class TimestampDiff(Func, TimeUnit):
3797    arg_types = {"this": True, "expression": True, "unit": False}
3798
3799
3800class TimestampTrunc(Func, TimeUnit):
3801    arg_types = {"this": True, "unit": True, "zone": False}
3802
3803
3804class TimeAdd(Func, TimeUnit):
3805    arg_types = {"this": True, "expression": True, "unit": False}
3806
3807
3808class TimeSub(Func, TimeUnit):
3809    arg_types = {"this": True, "expression": True, "unit": False}
3810
3811
3812class TimeDiff(Func, TimeUnit):
3813    arg_types = {"this": True, "expression": True, "unit": False}
3814
3815
3816class TimeTrunc(Func, TimeUnit):
3817    arg_types = {"this": True, "unit": True, "zone": False}
3818
3819
3820class DateFromParts(Func):
3821    _sql_names = ["DATEFROMPARTS"]
3822    arg_types = {"year": True, "month": True, "day": True}
3823
3824
3825class DateStrToDate(Func):
3826    pass
3827
3828
3829class DateToDateStr(Func):
3830    pass
3831
3832
3833class DateToDi(Func):
3834    pass
3835
3836
3837class Day(Func):
3838    pass
3839
3840
3841class Decode(Func):
3842    arg_types = {"this": True, "charset": True, "replace": False}
3843
3844
3845class DiToDate(Func):
3846    pass
3847
3848
3849class Encode(Func):
3850    arg_types = {"this": True, "charset": True}
3851
3852
3853class Exp(Func):
3854    pass
3855
3856
3857class Explode(Func):
3858    pass
3859
3860
3861class Floor(Func):
3862    arg_types = {"this": True, "decimals": False}
3863
3864
3865class FromBase64(Func):
3866    pass
3867
3868
3869class ToBase64(Func):
3870    pass
3871
3872
3873class Greatest(Func):
3874    arg_types = {"this": True, "expressions": False}
3875    is_var_len_args = True
3876
3877
3878class GroupConcat(Func):
3879    arg_types = {"this": True, "separator": False}
3880
3881
3882class Hex(Func):
3883    pass
3884
3885
3886class If(Func):
3887    arg_types = {"this": True, "true": True, "false": False}
3888
3889
3890class IfNull(Func):
3891    arg_types = {"this": True, "expression": False}
3892    _sql_names = ["IFNULL", "NVL"]
3893
3894
3895class Initcap(Func):
3896    pass
3897
3898
3899class JSONKeyValue(Expression):
3900    arg_types = {"this": True, "expression": True}
3901
3902
3903class JSONObject(Func):
3904    arg_types = {
3905        "expressions": False,
3906        "null_handling": False,
3907        "unique_keys": False,
3908        "return_type": False,
3909        "format_json": False,
3910        "encoding": False,
3911    }
3912
3913
3914class OpenJSONColumnDef(Expression):
3915    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
3916
3917
3918class OpenJSON(Func):
3919    arg_types = {"this": True, "path": False, "expressions": False}
3920
3921
3922class JSONBContains(Binary):
3923    _sql_names = ["JSONB_CONTAINS"]
3924
3925
3926class JSONExtract(Binary, Func):
3927    _sql_names = ["JSON_EXTRACT"]
3928
3929
3930class JSONExtractScalar(JSONExtract):
3931    _sql_names = ["JSON_EXTRACT_SCALAR"]
3932
3933
3934class JSONBExtract(JSONExtract):
3935    _sql_names = ["JSONB_EXTRACT"]
3936
3937
3938class JSONBExtractScalar(JSONExtract):
3939    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3940
3941
3942class JSONFormat(Func):
3943    arg_types = {"this": False, "options": False}
3944    _sql_names = ["JSON_FORMAT"]
3945
3946
3947class Least(Func):
3948    arg_types = {"expressions": False}
3949    is_var_len_args = True
3950
3951
3952class Length(Func):
3953    pass
3954
3955
3956class Levenshtein(Func):
3957    arg_types = {
3958        "this": True,
3959        "expression": False,
3960        "ins_cost": False,
3961        "del_cost": False,
3962        "sub_cost": False,
3963    }
3964
3965
3966class Ln(Func):
3967    pass
3968
3969
3970class Log(Func):
3971    arg_types = {"this": True, "expression": False}
3972
3973
3974class Log2(Func):
3975    pass
3976
3977
3978class Log10(Func):
3979    pass
3980
3981
3982class LogicalOr(AggFunc):
3983    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3984
3985
3986class LogicalAnd(AggFunc):
3987    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3988
3989
3990class Lower(Func):
3991    _sql_names = ["LOWER", "LCASE"]
3992
3993
3994class Map(Func):
3995    arg_types = {"keys": False, "values": False}
3996
3997
3998class StarMap(Func):
3999    pass
4000
4001
4002class VarMap(Func):
4003    arg_types = {"keys": True, "values": True}
4004    is_var_len_args = True
4005
4006
4007# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4008class MatchAgainst(Func):
4009    arg_types = {"this": True, "expressions": True, "modifier": False}
4010
4011
4012class Max(AggFunc):
4013    arg_types = {"this": True, "expressions": False}
4014    is_var_len_args = True
4015
4016
4017class MD5(Func):
4018    _sql_names = ["MD5"]
4019
4020
4021class Min(AggFunc):
4022    arg_types = {"this": True, "expressions": False}
4023    is_var_len_args = True
4024
4025
4026class Month(Func):
4027    pass
4028
4029
4030class Nvl2(Func):
4031    arg_types = {"this": True, "true": True, "false": False}
4032
4033
4034class Posexplode(Func):
4035    pass
4036
4037
4038class Pow(Binary, Func):
4039    _sql_names = ["POWER", "POW"]
4040
4041
4042class PercentileCont(AggFunc):
4043    arg_types = {"this": True, "expression": False}
4044
4045
4046class PercentileDisc(AggFunc):
4047    arg_types = {"this": True, "expression": False}
4048
4049
4050class Quantile(AggFunc):
4051    arg_types = {"this": True, "quantile": True}
4052
4053
4054class ApproxQuantile(Quantile):
4055    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4056
4057
4058class RangeN(Func):
4059    arg_types = {"this": True, "expressions": True, "each": False}
4060
4061
4062class ReadCSV(Func):
4063    _sql_names = ["READ_CSV"]
4064    is_var_len_args = True
4065    arg_types = {"this": True, "expressions": False}
4066
4067
4068class Reduce(Func):
4069    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4070
4071
4072class RegexpExtract(Func):
4073    arg_types = {
4074        "this": True,
4075        "expression": True,
4076        "position": False,
4077        "occurrence": False,
4078        "group": False,
4079    }
4080
4081
4082class RegexpLike(Func):
4083    arg_types = {"this": True, "expression": True, "flag": False}
4084
4085
4086class RegexpILike(Func):
4087    arg_types = {"this": True, "expression": True, "flag": False}
4088
4089
4090# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4091# limit is the number of times a pattern is applied
4092class RegexpSplit(Func):
4093    arg_types = {"this": True, "expression": True, "limit": False}
4094
4095
4096class Repeat(Func):
4097    arg_types = {"this": True, "times": True}
4098
4099
4100class Round(Func):
4101    arg_types = {"this": True, "decimals": False}
4102
4103
4104class RowNumber(Func):
4105    arg_types: t.Dict[str, t.Any] = {}
4106
4107
4108class SafeDivide(Func):
4109    arg_types = {"this": True, "expression": True}
4110
4111
4112class SetAgg(AggFunc):
4113    pass
4114
4115
4116class SHA(Func):
4117    _sql_names = ["SHA", "SHA1"]
4118
4119
4120class SHA2(Func):
4121    _sql_names = ["SHA2"]
4122    arg_types = {"this": True, "length": False}
4123
4124
4125class SortArray(Func):
4126    arg_types = {"this": True, "asc": False}
4127
4128
4129class Split(Func):
4130    arg_types = {"this": True, "expression": True, "limit": False}
4131
4132
4133# Start may be omitted in the case of postgres
4134# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4135class Substring(Func):
4136    arg_types = {"this": True, "start": False, "length": False}
4137
4138
4139class StandardHash(Func):
4140    arg_types = {"this": True, "expression": False}
4141
4142
4143class StrPosition(Func):
4144    arg_types = {
4145        "this": True,
4146        "substr": True,
4147        "position": False,
4148        "instance": False,
4149    }
4150
4151
4152class StrToDate(Func):
4153    arg_types = {"this": True, "format": True}
4154
4155
4156class StrToTime(Func):
4157    arg_types = {"this": True, "format": True}
4158
4159
4160# Spark allows unix_timestamp()
4161# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4162class StrToUnix(Func):
4163    arg_types = {"this": False, "format": False}
4164
4165
4166class NumberToStr(Func):
4167    arg_types = {"this": True, "format": True}
4168
4169
4170class Struct(Func):
4171    arg_types = {"expressions": True}
4172    is_var_len_args = True
4173
4174
4175class StructExtract(Func):
4176    arg_types = {"this": True, "expression": True}
4177
4178
4179class Sum(AggFunc):
4180    pass
4181
4182
4183class Sqrt(Func):
4184    pass
4185
4186
4187class Stddev(AggFunc):
4188    pass
4189
4190
4191class StddevPop(AggFunc):
4192    pass
4193
4194
4195class StddevSamp(AggFunc):
4196    pass
4197
4198
4199class TimeToStr(Func):
4200    arg_types = {"this": True, "format": True}
4201
4202
4203class TimeToTimeStr(Func):
4204    pass
4205
4206
4207class TimeToUnix(Func):
4208    pass
4209
4210
4211class TimeStrToDate(Func):
4212    pass
4213
4214
4215class TimeStrToTime(Func):
4216    pass
4217
4218
4219class TimeStrToUnix(Func):
4220    pass
4221
4222
4223class Trim(Func):
4224    arg_types = {
4225        "this": True,
4226        "expression": False,
4227        "position": False,
4228        "collation": False,
4229    }
4230
4231
4232class TsOrDsAdd(Func, TimeUnit):
4233    arg_types = {"this": True, "expression": True, "unit": False}
4234
4235
4236class TsOrDsToDateStr(Func):
4237    pass
4238
4239
4240class TsOrDsToDate(Func):
4241    arg_types = {"this": True, "format": False}
4242
4243
4244class TsOrDiToDi(Func):
4245    pass
4246
4247
4248class Unhex(Func):
4249    pass
4250
4251
4252class UnixToStr(Func):
4253    arg_types = {"this": True, "format": False}
4254
4255
4256# https://prestodb.io/docs/current/functions/datetime.html
4257# presto has weird zone/hours/minutes
4258class UnixToTime(Func):
4259    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4260
4261    SECONDS = Literal.string("seconds")
4262    MILLIS = Literal.string("millis")
4263    MICROS = Literal.string("micros")
4264
4265
4266class UnixToTimeStr(Func):
4267    pass
4268
4269
4270class Upper(Func):
4271    _sql_names = ["UPPER", "UCASE"]
4272
4273
4274class Variance(AggFunc):
4275    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4276
4277
4278class VariancePop(AggFunc):
4279    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4280
4281
4282class Week(Func):
4283    arg_types = {"this": True, "mode": False}
4284
4285
4286class XMLTable(Func):
4287    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4288
4289
4290class Year(Func):
4291    pass
4292
4293
4294class Use(Expression):
4295    arg_types = {"this": True, "kind": False}
4296
4297
4298class Merge(Expression):
4299    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4300
4301
4302class When(Func):
4303    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4304
4305
4306# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4307# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4308class NextValueFor(Func):
4309    arg_types = {"this": True, "order": False}
4310
4311
4312def _norm_arg(arg):
4313    return arg.lower() if type(arg) is str else arg
4314
4315
4316ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4317
4318
4319# Helpers
4320@t.overload
4321def maybe_parse(
4322    sql_or_expression: ExpOrStr,
4323    *,
4324    into: t.Type[E],
4325    dialect: DialectType = None,
4326    prefix: t.Optional[str] = None,
4327    copy: bool = False,
4328    **opts,
4329) -> E:
4330    ...
4331
4332
4333@t.overload
4334def maybe_parse(
4335    sql_or_expression: str | E,
4336    *,
4337    into: t.Optional[IntoType] = None,
4338    dialect: DialectType = None,
4339    prefix: t.Optional[str] = None,
4340    copy: bool = False,
4341    **opts,
4342) -> E:
4343    ...
4344
4345
4346def maybe_parse(
4347    sql_or_expression: ExpOrStr,
4348    *,
4349    into: t.Optional[IntoType] = None,
4350    dialect: DialectType = None,
4351    prefix: t.Optional[str] = None,
4352    copy: bool = False,
4353    **opts,
4354) -> Expression:
4355    """Gracefully handle a possible string or expression.
4356
4357    Example:
4358        >>> maybe_parse("1")
4359        (LITERAL this: 1, is_string: False)
4360        >>> maybe_parse(to_identifier("x"))
4361        (IDENTIFIER this: x, quoted: False)
4362
4363    Args:
4364        sql_or_expression: the SQL code string or an expression
4365        into: the SQLGlot Expression to parse into
4366        dialect: the dialect used to parse the input expressions (in the case that an
4367            input expression is a SQL string).
4368        prefix: a string to prefix the sql with before it gets parsed
4369            (automatically includes a space)
4370        copy: whether or not to copy the expression.
4371        **opts: other options to use to parse the input expressions (again, in the case
4372            that an input expression is a SQL string).
4373
4374    Returns:
4375        Expression: the parsed or given expression.
4376    """
4377    if isinstance(sql_or_expression, Expression):
4378        if copy:
4379            return sql_or_expression.copy()
4380        return sql_or_expression
4381
4382    import sqlglot
4383
4384    sql = str(sql_or_expression)
4385    if prefix:
4386        sql = f"{prefix} {sql}"
4387    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4388
4389
4390def _maybe_copy(instance, copy=True):
4391    return instance.copy() if copy else instance
4392
4393
4394def _is_wrong_expression(expression, into):
4395    return isinstance(expression, Expression) and not isinstance(expression, into)
4396
4397
4398def _apply_builder(
4399    expression,
4400    instance,
4401    arg,
4402    copy=True,
4403    prefix=None,
4404    into=None,
4405    dialect=None,
4406    **opts,
4407):
4408    if _is_wrong_expression(expression, into):
4409        expression = into(this=expression)
4410    instance = _maybe_copy(instance, copy)
4411    expression = maybe_parse(
4412        sql_or_expression=expression,
4413        prefix=prefix,
4414        into=into,
4415        dialect=dialect,
4416        **opts,
4417    )
4418    instance.set(arg, expression)
4419    return instance
4420
4421
4422def _apply_child_list_builder(
4423    *expressions,
4424    instance,
4425    arg,
4426    append=True,
4427    copy=True,
4428    prefix=None,
4429    into=None,
4430    dialect=None,
4431    properties=None,
4432    **opts,
4433):
4434    instance = _maybe_copy(instance, copy)
4435    parsed = []
4436    for expression in expressions:
4437        if _is_wrong_expression(expression, into):
4438            expression = into(expressions=[expression])
4439        expression = maybe_parse(
4440            expression,
4441            into=into,
4442            dialect=dialect,
4443            prefix=prefix,
4444            **opts,
4445        )
4446        parsed.extend(expression.expressions)
4447
4448    existing = instance.args.get(arg)
4449    if append and existing:
4450        parsed = existing.expressions + parsed
4451
4452    child = into(expressions=parsed)
4453    for k, v in (properties or {}).items():
4454        child.set(k, v)
4455    instance.set(arg, child)
4456    return instance
4457
4458
4459def _apply_list_builder(
4460    *expressions,
4461    instance,
4462    arg,
4463    append=True,
4464    copy=True,
4465    prefix=None,
4466    into=None,
4467    dialect=None,
4468    **opts,
4469):
4470    inst = _maybe_copy(instance, copy)
4471
4472    expressions = [
4473        maybe_parse(
4474            sql_or_expression=expression,
4475            into=into,
4476            prefix=prefix,
4477            dialect=dialect,
4478            **opts,
4479        )
4480        for expression in expressions
4481    ]
4482
4483    existing_expressions = inst.args.get(arg)
4484    if append and existing_expressions:
4485        expressions = existing_expressions + expressions
4486
4487    inst.set(arg, expressions)
4488    return inst
4489
4490
4491def _apply_conjunction_builder(
4492    *expressions,
4493    instance,
4494    arg,
4495    into=None,
4496    append=True,
4497    copy=True,
4498    dialect=None,
4499    **opts,
4500):
4501    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4502    if not expressions:
4503        return instance
4504
4505    inst = _maybe_copy(instance, copy)
4506
4507    existing = inst.args.get(arg)
4508    if append and existing is not None:
4509        expressions = [existing.this if into else existing] + list(expressions)
4510
4511    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4512
4513    inst.set(arg, into(this=node) if into else node)
4514    return inst
4515
4516
4517def _combine(expressions, operator, dialect=None, copy=True, **opts):
4518    expressions = [
4519        condition(expression, dialect=dialect, copy=copy, **opts) for expression in expressions
4520    ]
4521    this = expressions[0]
4522    if expressions[1:]:
4523        this = _wrap(this, Connector)
4524    for expression in expressions[1:]:
4525        this = operator(this=this, expression=_wrap(expression, Connector))
4526    return this
4527
4528
4529def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4530    if isinstance(expression, kind):
4531        return Paren(this=expression)
4532    return expression
4533
4534
4535def union(left, right, distinct=True, dialect=None, **opts):
4536    """
4537    Initializes a syntax tree from one UNION expression.
4538
4539    Example:
4540        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4541        'SELECT * FROM foo UNION SELECT * FROM bla'
4542
4543    Args:
4544        left (str | Expression): the SQL code string corresponding to the left-hand side.
4545            If an `Expression` instance is passed, it will be used as-is.
4546        right (str | Expression): the SQL code string corresponding to the right-hand side.
4547            If an `Expression` instance is passed, it will be used as-is.
4548        distinct (bool): set the DISTINCT flag if and only if this is true.
4549        dialect (str): the dialect used to parse the input expression.
4550        opts (kwargs): other options to use to parse the input expressions.
4551    Returns:
4552        Union: the syntax tree for the UNION expression.
4553    """
4554    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4555    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4556
4557    return Union(this=left, expression=right, distinct=distinct)
4558
4559
4560def intersect(left, right, distinct=True, dialect=None, **opts):
4561    """
4562    Initializes a syntax tree from one INTERSECT expression.
4563
4564    Example:
4565        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4566        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4567
4568    Args:
4569        left (str | Expression): the SQL code string corresponding to the left-hand side.
4570            If an `Expression` instance is passed, it will be used as-is.
4571        right (str | Expression): the SQL code string corresponding to the right-hand side.
4572            If an `Expression` instance is passed, it will be used as-is.
4573        distinct (bool): set the DISTINCT flag if and only if this is true.
4574        dialect (str): the dialect used to parse the input expression.
4575        opts (kwargs): other options to use to parse the input expressions.
4576    Returns:
4577        Intersect: the syntax tree for the INTERSECT expression.
4578    """
4579    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4580    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4581
4582    return Intersect(this=left, expression=right, distinct=distinct)
4583
4584
4585def except_(left, right, distinct=True, dialect=None, **opts):
4586    """
4587    Initializes a syntax tree from one EXCEPT expression.
4588
4589    Example:
4590        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4591        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4592
4593    Args:
4594        left (str | Expression): the SQL code string corresponding to the left-hand side.
4595            If an `Expression` instance is passed, it will be used as-is.
4596        right (str | Expression): the SQL code string corresponding to the right-hand side.
4597            If an `Expression` instance is passed, it will be used as-is.
4598        distinct (bool): set the DISTINCT flag if and only if this is true.
4599        dialect (str): the dialect used to parse the input expression.
4600        opts (kwargs): other options to use to parse the input expressions.
4601    Returns:
4602        Except: the syntax tree for the EXCEPT statement.
4603    """
4604    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4605    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4606
4607    return Except(this=left, expression=right, distinct=distinct)
4608
4609
4610def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4611    """
4612    Initializes a syntax tree from one or multiple SELECT expressions.
4613
4614    Example:
4615        >>> select("col1", "col2").from_("tbl").sql()
4616        'SELECT col1, col2 FROM tbl'
4617
4618    Args:
4619        *expressions: the SQL code string to parse as the expressions of a
4620            SELECT statement. If an Expression instance is passed, this is used as-is.
4621        dialect: the dialect used to parse the input expressions (in the case that an
4622            input expression is a SQL string).
4623        **opts: other options to use to parse the input expressions (again, in the case
4624            that an input expression is a SQL string).
4625
4626    Returns:
4627        Select: the syntax tree for the SELECT statement.
4628    """
4629    return Select().select(*expressions, dialect=dialect, **opts)
4630
4631
4632def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4633    """
4634    Initializes a syntax tree from a FROM expression.
4635
4636    Example:
4637        >>> from_("tbl").select("col1", "col2").sql()
4638        'SELECT col1, col2 FROM tbl'
4639
4640    Args:
4641        *expression: the SQL code string to parse as the FROM expressions of a
4642            SELECT statement. If an Expression instance is passed, this is used as-is.
4643        dialect: the dialect used to parse the input expression (in the case that the
4644            input expression is a SQL string).
4645        **opts: other options to use to parse the input expressions (again, in the case
4646            that the input expression is a SQL string).
4647
4648    Returns:
4649        Select: the syntax tree for the SELECT statement.
4650    """
4651    return Select().from_(expression, dialect=dialect, **opts)
4652
4653
4654def update(
4655    table: str | Table,
4656    properties: dict,
4657    where: t.Optional[ExpOrStr] = None,
4658    from_: t.Optional[ExpOrStr] = None,
4659    dialect: DialectType = None,
4660    **opts,
4661) -> Update:
4662    """
4663    Creates an update statement.
4664
4665    Example:
4666        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4667        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4668
4669    Args:
4670        *properties: dictionary of properties to set which are
4671            auto converted to sql objects eg None -> NULL
4672        where: sql conditional parsed into a WHERE statement
4673        from_: sql statement parsed into a FROM statement
4674        dialect: the dialect used to parse the input expressions.
4675        **opts: other options to use to parse the input expressions.
4676
4677    Returns:
4678        Update: the syntax tree for the UPDATE statement.
4679    """
4680    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4681    update_expr.set(
4682        "expressions",
4683        [
4684            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4685            for k, v in properties.items()
4686        ],
4687    )
4688    if from_:
4689        update_expr.set(
4690            "from",
4691            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4692        )
4693    if isinstance(where, Condition):
4694        where = Where(this=where)
4695    if where:
4696        update_expr.set(
4697            "where",
4698            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4699        )
4700    return update_expr
4701
4702
4703def delete(
4704    table: ExpOrStr,
4705    where: t.Optional[ExpOrStr] = None,
4706    returning: t.Optional[ExpOrStr] = None,
4707    dialect: DialectType = None,
4708    **opts,
4709) -> Delete:
4710    """
4711    Builds a delete statement.
4712
4713    Example:
4714        >>> delete("my_table", where="id > 1").sql()
4715        'DELETE FROM my_table WHERE id > 1'
4716
4717    Args:
4718        where: sql conditional parsed into a WHERE statement
4719        returning: sql conditional parsed into a RETURNING statement
4720        dialect: the dialect used to parse the input expressions.
4721        **opts: other options to use to parse the input expressions.
4722
4723    Returns:
4724        Delete: the syntax tree for the DELETE statement.
4725    """
4726    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4727    if where:
4728        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4729    if returning:
4730        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4731    return delete_expr
4732
4733
4734def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4735    """
4736    Initialize a logical condition expression.
4737
4738    Example:
4739        >>> condition("x=1").sql()
4740        'x = 1'
4741
4742        This is helpful for composing larger logical syntax trees:
4743        >>> where = condition("x=1")
4744        >>> where = where.and_("y=1")
4745        >>> Select().from_("tbl").select("*").where(where).sql()
4746        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4747
4748    Args:
4749        *expression (str | Expression): the SQL code string to parse.
4750            If an Expression instance is passed, this is used as-is.
4751        dialect (str): the dialect used to parse the input expression (in the case that the
4752            input expression is a SQL string).
4753        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4754        **opts: other options to use to parse the input expressions (again, in the case
4755            that the input expression is a SQL string).
4756
4757    Returns:
4758        Condition: the expression
4759    """
4760    return maybe_parse(  # type: ignore
4761        expression,
4762        into=Condition,
4763        dialect=dialect,
4764        copy=copy,
4765        **opts,
4766    )
4767
4768
4769def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4770    """
4771    Combine multiple conditions with an AND logical operator.
4772
4773    Example:
4774        >>> and_("x=1", and_("y=1", "z=1")).sql()
4775        'x = 1 AND (y = 1 AND z = 1)'
4776
4777    Args:
4778        *expressions (str | Expression): the SQL code strings to parse.
4779            If an Expression instance is passed, this is used as-is.
4780        dialect (str): the dialect used to parse the input expression.
4781        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4782        **opts: other options to use to parse the input expressions.
4783
4784    Returns:
4785        And: the new condition
4786    """
4787    return _combine(expressions, And, dialect, copy=copy, **opts)
4788
4789
4790def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4791    """
4792    Combine multiple conditions with an OR logical operator.
4793
4794    Example:
4795        >>> or_("x=1", or_("y=1", "z=1")).sql()
4796        'x = 1 OR (y = 1 OR z = 1)'
4797
4798    Args:
4799        *expressions (str | Expression): the SQL code strings to parse.
4800            If an Expression instance is passed, this is used as-is.
4801        dialect (str): the dialect used to parse the input expression.
4802        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4803        **opts: other options to use to parse the input expressions.
4804
4805    Returns:
4806        Or: the new condition
4807    """
4808    return _combine(expressions, Or, dialect, copy=copy, **opts)
4809
4810
4811def not_(expression, dialect=None, copy=True, **opts) -> Not:
4812    """
4813    Wrap a condition with a NOT operator.
4814
4815    Example:
4816        >>> not_("this_suit='black'").sql()
4817        "NOT this_suit = 'black'"
4818
4819    Args:
4820        expression (str | Expression): the SQL code strings to parse.
4821            If an Expression instance is passed, this is used as-is.
4822        dialect (str): the dialect used to parse the input expression.
4823        **opts: other options to use to parse the input expressions.
4824
4825    Returns:
4826        Not: the new condition
4827    """
4828    this = condition(
4829        expression,
4830        dialect=dialect,
4831        copy=copy,
4832        **opts,
4833    )
4834    return Not(this=_wrap(this, Connector))
4835
4836
4837def paren(expression, copy=True) -> Paren:
4838    return Paren(this=_maybe_copy(expression, copy))
4839
4840
4841SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4842
4843
4844@t.overload
4845def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
4846    ...
4847
4848
4849@t.overload
4850def to_identifier(
4851    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
4852) -> Identifier:
4853    ...
4854
4855
4856def to_identifier(name, quoted=None, copy=True):
4857    """Builds an identifier.
4858
4859    Args:
4860        name: The name to turn into an identifier.
4861        quoted: Whether or not force quote the identifier.
4862        copy: Whether or not to copy a passed in Identefier node.
4863
4864    Returns:
4865        The identifier ast node.
4866    """
4867
4868    if name is None:
4869        return None
4870
4871    if isinstance(name, Identifier):
4872        identifier = _maybe_copy(name, copy)
4873    elif isinstance(name, str):
4874        identifier = Identifier(
4875            this=name,
4876            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4877        )
4878    else:
4879        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4880    return identifier
4881
4882
4883INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4884
4885
4886def to_interval(interval: str | Literal) -> Interval:
4887    """Builds an interval expression from a string like '1 day' or '5 months'."""
4888    if isinstance(interval, Literal):
4889        if not interval.is_string:
4890            raise ValueError("Invalid interval string.")
4891
4892        interval = interval.this
4893
4894    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4895
4896    if not interval_parts:
4897        raise ValueError("Invalid interval string.")
4898
4899    return Interval(
4900        this=Literal.string(interval_parts.group(1)),
4901        unit=Var(this=interval_parts.group(2)),
4902    )
4903
4904
4905@t.overload
4906def to_table(sql_path: str | Table, **kwargs) -> Table:
4907    ...
4908
4909
4910@t.overload
4911def to_table(sql_path: None, **kwargs) -> None:
4912    ...
4913
4914
4915def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4916    """
4917    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4918    If a table is passed in then that table is returned.
4919
4920    Args:
4921        sql_path: a `[catalog].[schema].[table]` string.
4922
4923    Returns:
4924        A table expression.
4925    """
4926    if sql_path is None or isinstance(sql_path, Table):
4927        return sql_path
4928    if not isinstance(sql_path, str):
4929        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4930
4931    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4932    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4933
4934
4935def to_column(sql_path: str | Column, **kwargs) -> Column:
4936    """
4937    Create a column from a `[table].[column]` sql path. Schema is optional.
4938
4939    If a column is passed in then that column is returned.
4940
4941    Args:
4942        sql_path: `[table].[column]` string
4943    Returns:
4944        Table: A column expression
4945    """
4946    if sql_path is None or isinstance(sql_path, Column):
4947        return sql_path
4948    if not isinstance(sql_path, str):
4949        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4950    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4951
4952
4953def alias_(
4954    expression: ExpOrStr,
4955    alias: str | Identifier,
4956    table: bool | t.Sequence[str | Identifier] = False,
4957    quoted: t.Optional[bool] = None,
4958    dialect: DialectType = None,
4959    copy: bool = True,
4960    **opts,
4961):
4962    """Create an Alias expression.
4963
4964    Example:
4965        >>> alias_('foo', 'bar').sql()
4966        'foo AS bar'
4967
4968        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4969        '(SELECT 1, 2) AS bar(a, b)'
4970
4971    Args:
4972        expression: the SQL code strings to parse.
4973            If an Expression instance is passed, this is used as-is.
4974        alias: the alias name to use. If the name has
4975            special characters it is quoted.
4976        table: Whether or not to create a table alias, can also be a list of columns.
4977        quoted: whether or not to quote the alias
4978        dialect: the dialect used to parse the input expression.
4979        copy: Whether or not to copy the expression.
4980        **opts: other options to use to parse the input expressions.
4981
4982    Returns:
4983        Alias: the aliased expression
4984    """
4985    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4986    alias = to_identifier(alias, quoted=quoted)
4987
4988    if table:
4989        table_alias = TableAlias(this=alias)
4990        exp.set("alias", table_alias)
4991
4992        if not isinstance(table, bool):
4993            for column in table:
4994                table_alias.append("columns", to_identifier(column, quoted=quoted))
4995
4996        return exp
4997
4998    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4999    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5000    # for the complete Window expression.
5001    #
5002    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5003
5004    if "alias" in exp.arg_types and not isinstance(exp, Window):
5005        exp.set("alias", alias)
5006        return exp
5007    return Alias(this=exp, alias=alias)
5008
5009
5010def subquery(expression, alias=None, dialect=None, **opts):
5011    """
5012    Build a subquery expression.
5013
5014    Example:
5015        >>> subquery('select x from tbl', 'bar').select('x').sql()
5016        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5017
5018    Args:
5019        expression (str | Expression): the SQL code strings to parse.
5020            If an Expression instance is passed, this is used as-is.
5021        alias (str | Expression): the alias name to use.
5022        dialect (str): the dialect used to parse the input expression.
5023        **opts: other options to use to parse the input expressions.
5024
5025    Returns:
5026        Select: a new select with the subquery expression included
5027    """
5028
5029    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5030    return Select().from_(expression, dialect=dialect, **opts)
5031
5032
5033def column(
5034    col: str | Identifier,
5035    table: t.Optional[str | Identifier] = None,
5036    db: t.Optional[str | Identifier] = None,
5037    catalog: t.Optional[str | Identifier] = None,
5038    quoted: t.Optional[bool] = None,
5039) -> Column:
5040    """
5041    Build a Column.
5042
5043    Args:
5044        col: column name
5045        table: table name
5046        db: db name
5047        catalog: catalog name
5048        quoted: whether or not to force quote each part
5049    Returns:
5050        Column: column instance
5051    """
5052    return Column(
5053        this=to_identifier(col, quoted=quoted),
5054        table=to_identifier(table, quoted=quoted),
5055        db=to_identifier(db, quoted=quoted),
5056        catalog=to_identifier(catalog, quoted=quoted),
5057    )
5058
5059
5060def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5061    """Cast an expression to a data type.
5062
5063    Example:
5064        >>> cast('x + 1', 'int').sql()
5065        'CAST(x + 1 AS INT)'
5066
5067    Args:
5068        expression: The expression to cast.
5069        to: The datatype to cast to.
5070
5071    Returns:
5072        A cast node.
5073    """
5074    expression = maybe_parse(expression, **opts)
5075    return Cast(this=expression, to=DataType.build(to, **opts))
5076
5077
5078def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5079    """Build a Table.
5080
5081    Args:
5082        table (str | Expression): column name
5083        db (str | Expression): db name
5084        catalog (str | Expression): catalog name
5085
5086    Returns:
5087        Table: table instance
5088    """
5089    return Table(
5090        this=to_identifier(table, quoted=quoted),
5091        db=to_identifier(db, quoted=quoted),
5092        catalog=to_identifier(catalog, quoted=quoted),
5093        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5094    )
5095
5096
5097def values(
5098    values: t.Iterable[t.Tuple[t.Any, ...]],
5099    alias: t.Optional[str] = None,
5100    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5101) -> Values:
5102    """Build VALUES statement.
5103
5104    Example:
5105        >>> values([(1, '2')]).sql()
5106        "VALUES (1, '2')"
5107
5108    Args:
5109        values: values statements that will be converted to SQL
5110        alias: optional alias
5111        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5112         If either are provided then an alias is also required.
5113
5114    Returns:
5115        Values: the Values expression object
5116    """
5117    if columns and not alias:
5118        raise ValueError("Alias is required when providing columns")
5119
5120    return Values(
5121        expressions=[convert(tup) for tup in values],
5122        alias=(
5123            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5124            if columns
5125            else (TableAlias(this=to_identifier(alias)) if alias else None)
5126        ),
5127    )
5128
5129
5130def var(name: t.Optional[ExpOrStr]) -> Var:
5131    """Build a SQL variable.
5132
5133    Example:
5134        >>> repr(var('x'))
5135        '(VAR this: x)'
5136
5137        >>> repr(var(column('x', table='y')))
5138        '(VAR this: x)'
5139
5140    Args:
5141        name: The name of the var or an expression who's name will become the var.
5142
5143    Returns:
5144        The new variable node.
5145    """
5146    if not name:
5147        raise ValueError("Cannot convert empty name into var.")
5148
5149    if isinstance(name, Expression):
5150        name = name.name
5151    return Var(this=name)
5152
5153
5154def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5155    """Build ALTER TABLE... RENAME... expression
5156
5157    Args:
5158        old_name: The old name of the table
5159        new_name: The new name of the table
5160
5161    Returns:
5162        Alter table expression
5163    """
5164    old_table = to_table(old_name)
5165    new_table = to_table(new_name)
5166    return AlterTable(
5167        this=old_table,
5168        actions=[
5169            RenameTable(this=new_table),
5170        ],
5171    )
5172
5173
5174def convert(value: t.Any, copy: bool = False) -> Expression:
5175    """Convert a python value into an expression object.
5176
5177    Raises an error if a conversion is not possible.
5178
5179    Args:
5180        value: A python object.
5181        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5182
5183    Returns:
5184        Expression: the equivalent expression object.
5185    """
5186    if isinstance(value, Expression):
5187        return _maybe_copy(value, copy)
5188    if isinstance(value, str):
5189        return Literal.string(value)
5190    if isinstance(value, bool):
5191        return Boolean(this=value)
5192    if value is None or (isinstance(value, float) and math.isnan(value)):
5193        return NULL
5194    if isinstance(value, numbers.Number):
5195        return Literal.number(value)
5196    if isinstance(value, datetime.datetime):
5197        datetime_literal = Literal.string(
5198            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5199        )
5200        return TimeStrToTime(this=datetime_literal)
5201    if isinstance(value, datetime.date):
5202        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5203        return DateStrToDate(this=date_literal)
5204    if isinstance(value, tuple):
5205        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5206    if isinstance(value, list):
5207        return Array(expressions=[convert(v, copy=copy) for v in value])
5208    if isinstance(value, dict):
5209        return Map(
5210            keys=[convert(k, copy=copy) for k in value],
5211            values=[convert(v, copy=copy) for v in value.values()],
5212        )
5213    raise ValueError(f"Cannot convert {value}")
5214
5215
5216def replace_children(expression, fun, *args, **kwargs):
5217    """
5218    Replace children of an expression with the result of a lambda fun(child) -> exp.
5219    """
5220    for k, v in expression.args.items():
5221        is_list_arg = type(v) is list
5222
5223        child_nodes = v if is_list_arg else [v]
5224        new_child_nodes = []
5225
5226        for cn in child_nodes:
5227            if isinstance(cn, Expression):
5228                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5229                    new_child_nodes.append(child_node)
5230                    child_node.parent = expression
5231                    child_node.arg_key = k
5232            else:
5233                new_child_nodes.append(cn)
5234
5235        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5236
5237
5238def column_table_names(expression):
5239    """
5240    Return all table names referenced through columns in an expression.
5241
5242    Example:
5243        >>> import sqlglot
5244        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5245        ['c', 'a']
5246
5247    Args:
5248        expression (sqlglot.Expression): expression to find table names
5249
5250    Returns:
5251        list: A list of unique names
5252    """
5253    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
5254
5255
5256def table_name(table) -> str:
5257    """Get the full name of a table as a string.
5258
5259    Args:
5260        table (exp.Table | str): table expression node or string.
5261
5262    Examples:
5263        >>> from sqlglot import exp, parse_one
5264        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5265        'a.b.c'
5266
5267    Returns:
5268        The table name.
5269    """
5270
5271    table = maybe_parse(table, into=Table)
5272
5273    if not table:
5274        raise ValueError(f"Cannot parse {table}")
5275
5276    return ".".join(
5277        part
5278        for part in (
5279            table.text("catalog"),
5280            table.text("db"),
5281            table.name,
5282        )
5283        if part
5284    )
5285
5286
5287def replace_tables(expression, mapping):
5288    """Replace all tables in expression according to the mapping.
5289
5290    Args:
5291        expression (sqlglot.Expression): expression node to be transformed and replaced.
5292        mapping (Dict[str, str]): mapping of table names.
5293
5294    Examples:
5295        >>> from sqlglot import exp, parse_one
5296        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5297        'SELECT * FROM c'
5298
5299    Returns:
5300        The mapped expression.
5301    """
5302
5303    def _replace_tables(node):
5304        if isinstance(node, Table):
5305            new_name = mapping.get(table_name(node))
5306            if new_name:
5307                return to_table(
5308                    new_name,
5309                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5310                )
5311        return node
5312
5313    return expression.transform(_replace_tables)
5314
5315
5316def replace_placeholders(expression, *args, **kwargs):
5317    """Replace placeholders in an expression.
5318
5319    Args:
5320        expression (sqlglot.Expression): expression node to be transformed and replaced.
5321        args: positional names that will substitute unnamed placeholders in the given order.
5322        kwargs: keyword arguments that will substitute named placeholders.
5323
5324    Examples:
5325        >>> from sqlglot import exp, parse_one
5326        >>> replace_placeholders(
5327        ...     parse_one("select * from :tbl where ? = ?"),
5328        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5329        ... ).sql()
5330        "SELECT * FROM foo WHERE str_col = 'b'"
5331
5332    Returns:
5333        The mapped expression.
5334    """
5335
5336    def _replace_placeholders(node, args, **kwargs):
5337        if isinstance(node, Placeholder):
5338            if node.name:
5339                new_name = kwargs.get(node.name)
5340                if new_name:
5341                    return convert(new_name)
5342            else:
5343                try:
5344                    return convert(next(args))
5345                except StopIteration:
5346                    pass
5347        return node
5348
5349    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5350
5351
5352def expand(
5353    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5354) -> Expression:
5355    """Transforms an expression by expanding all referenced sources into subqueries.
5356
5357    Examples:
5358        >>> from sqlglot import parse_one
5359        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5360        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5361
5362        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5363        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5364
5365    Args:
5366        expression: The expression to expand.
5367        sources: A dictionary of name to Subqueryables.
5368        copy: Whether or not to copy the expression during transformation. Defaults to True.
5369
5370    Returns:
5371        The transformed expression.
5372    """
5373
5374    def _expand(node: Expression):
5375        if isinstance(node, Table):
5376            name = table_name(node)
5377            source = sources.get(name)
5378            if source:
5379                subquery = source.subquery(node.alias or name)
5380                subquery.comments = [f"source: {name}"]
5381                return subquery.transform(_expand, copy=False)
5382        return node
5383
5384    return expression.transform(_expand, copy=copy)
5385
5386
5387def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5388    """
5389    Returns a Func expression.
5390
5391    Examples:
5392        >>> func("abs", 5).sql()
5393        'ABS(5)'
5394
5395        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5396        'CAST(5 AS DOUBLE)'
5397
5398    Args:
5399        name: the name of the function to build.
5400        args: the args used to instantiate the function of interest.
5401        dialect: the source dialect.
5402        kwargs: the kwargs used to instantiate the function of interest.
5403
5404    Note:
5405        The arguments `args` and `kwargs` are mutually exclusive.
5406
5407    Returns:
5408        An instance of the function of interest, or an anonymous function, if `name` doesn't
5409        correspond to an existing `sqlglot.expressions.Func` class.
5410    """
5411    if args and kwargs:
5412        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5413
5414    from sqlglot.dialects.dialect import Dialect
5415
5416    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5417    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5418
5419    parser = Dialect.get_or_raise(dialect)().parser()
5420    from_args_list = parser.FUNCTIONS.get(name.upper())
5421
5422    if from_args_list:
5423        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5424    else:
5425        kwargs = kwargs or {"expressions": converted}
5426        function = Anonymous(this=name, **kwargs)
5427
5428    for error_message in function.error_messages(converted):
5429        raise ValueError(error_message)
5430
5431    return function
5432
5433
5434def true():
5435    """
5436    Returns a true Boolean expression.
5437    """
5438    return Boolean(this=True)
5439
5440
5441def false():
5442    """
5443    Returns a false Boolean expression.
5444    """
5445    return Boolean(this=False)
5446
5447
5448def null():
5449    """
5450    Returns a Null expression.
5451    """
5452    return Null()
5453
5454
5455# TODO: deprecate this
5456TRUE = Boolean(this=True)
5457FALSE = Boolean(this=False)
5458NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68        parent: a reference to the parent expression (or None, in case of root expressions).
 69        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 70            uses to refer to it.
 71        comments: a list of comments that are associated with a given expression. This is used in
 72            order to preserve comments when transpiling SQL code.
 73        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 74            optimizer, in order to enable some transformations that require type information.
 75
 76    Example:
 77        >>> class Foo(Expression):
 78        ...     arg_types = {"this": True, "expression": False}
 79
 80        The above definition informs us that Foo is an Expression that requires an argument called
 81        "this" and may also optionally receive an argument called "expression".
 82
 83    Args:
 84        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
267
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)
280
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)
291
292    def _set_parent(self, arg_key, value):
293        if hasattr(value, "parent"):
294            value.parent = self
295            value.arg_key = arg_key
296        elif type(value) is list:
297            for v in value:
298                if hasattr(v, "parent"):
299                    v.parent = self
300                    v.arg_key = arg_key
301
302    @property
303    def depth(self):
304        """
305        Returns the depth of this tree.
306        """
307        if self.parent:
308            return self.parent.depth + 1
309        return 0
310
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs
321
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)
334
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self):
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self):
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self):
474        return self.sql()
475
476    def __repr__(self):
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression
571
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self
581
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self
598
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors
632
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)
640
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
262    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
263        if self.comments is None:
264            self.comments = []
265        if comments:
266            self.comments.extend(comments)
def append(self, arg_key, value):
268    def append(self, arg_key, value):
269        """
270        Appends value to arg_key if it's a list or sets it as a new list.
271
272        Args:
273            arg_key (str): name of the list expression arg
274            value (Any): value to append to the list
275        """
276        if not isinstance(self.args.get(arg_key), list):
277            self.args[arg_key] = []
278        self.args[arg_key].append(value)
279        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
281    def set(self, arg_key, value):
282        """
283        Sets `arg_key` to `value`.
284
285        Args:
286            arg_key (str): name of the expression arg.
287            value: value to set the arg to.
288        """
289        self.args[arg_key] = value
290        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
582    def assert_is(self, type_):
583        """
584        Assert that this `Expression` is an instance of `type_`.
585
586        If it is NOT an instance of `type_`, this raises an assertion error.
587        Otherwise, this returns this expression.
588
589        Examples:
590            This is useful for type security in chained expressions:
591
592            >>> import sqlglot
593            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
594            'SELECT x, z FROM y'
595        """
596        assert isinstance(self, type_)
597        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
599    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
600        """
601        Checks if this expression is valid (e.g. all mandatory args are set).
602
603        Args:
604            args: a sequence of values that were used to instantiate a Func expression. This is used
605                to check that the provided arguments don't exceed the function argument limit.
606
607        Returns:
608            A list of error messages for all possible errors that were found.
609        """
610        errors: t.List[str] = []
611
612        for k in self.args:
613            if k not in self.arg_types:
614                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
615        for k, mandatory in self.arg_types.items():
616            v = self.args.get(k)
617            if mandatory and (v is None or (isinstance(v, list) and not v)):
618                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
619
620        if (
621            args
622            and isinstance(self, Func)
623            and len(args) > len(self.arg_types)
624            and not self.is_var_len_args
625        ):
626            errors.append(
627                f"The number of provided arguments ({len(args)}) is greater than "
628                f"the maximum number of supported arguments ({len(self.arg_types)})"
629            )
630
631        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
633    def dump(self):
634        """
635        Dump this Expression to a JSON-serializable dict.
636        """
637        from sqlglot.serde import dump
638
639        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
659class Condition(Expression):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
679
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
699
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)
715
716    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
717        this = self.copy()
718        other = convert(other, copy=True)
719        if not isinstance(this, klass) and not isinstance(other, klass):
720            this = _wrap(this, Binary)
721            other = _wrap(other, Binary)
722        if reverse:
723            return klass(this=other, expression=this)
724        return klass(this=this, expression=other)
725
726    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
727        return Bracket(
728            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
729        )
730
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
739
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
746
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
749
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
752
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
755
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
758
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
761
762    def __lt__(self, other: t.Any) -> LT:
763        return self._binop(LT, other)
764
765    def __le__(self, other: t.Any) -> LTE:
766        return self._binop(LTE, other)
767
768    def __gt__(self, other: t.Any) -> GT:
769        return self._binop(GT, other)
770
771    def __ge__(self, other: t.Any) -> GTE:
772        return self._binop(GTE, other)
773
774    def __add__(self, other: t.Any) -> Add:
775        return self._binop(Add, other)
776
777    def __radd__(self, other: t.Any) -> Add:
778        return self._binop(Add, other, reverse=True)
779
780    def __sub__(self, other: t.Any) -> Sub:
781        return self._binop(Sub, other)
782
783    def __rsub__(self, other: t.Any) -> Sub:
784        return self._binop(Sub, other, reverse=True)
785
786    def __mul__(self, other: t.Any) -> Mul:
787        return self._binop(Mul, other)
788
789    def __rmul__(self, other: t.Any) -> Mul:
790        return self._binop(Mul, other, reverse=True)
791
792    def __truediv__(self, other: t.Any) -> Div:
793        return self._binop(Div, other)
794
795    def __rtruediv__(self, other: t.Any) -> Div:
796        return self._binop(Div, other, reverse=True)
797
798    def __floordiv__(self, other: t.Any) -> IntDiv:
799        return self._binop(IntDiv, other)
800
801    def __rfloordiv__(self, other: t.Any) -> IntDiv:
802        return self._binop(IntDiv, other, reverse=True)
803
804    def __mod__(self, other: t.Any) -> Mod:
805        return self._binop(Mod, other)
806
807    def __rmod__(self, other: t.Any) -> Mod:
808        return self._binop(Mod, other, reverse=True)
809
810    def __pow__(self, other: t.Any) -> Pow:
811        return self._binop(Pow, other)
812
813    def __rpow__(self, other: t.Any) -> Pow:
814        return self._binop(Pow, other, reverse=True)
815
816    def __and__(self, other: t.Any) -> And:
817        return self._binop(And, other)
818
819    def __rand__(self, other: t.Any) -> And:
820        return self._binop(And, other, reverse=True)
821
822    def __or__(self, other: t.Any) -> Or:
823        return self._binop(Or, other)
824
825    def __ror__(self, other: t.Any) -> Or:
826        return self._binop(Or, other, reverse=True)
827
828    def __neg__(self) -> Neg:
829        return Neg(this=_wrap(self.copy(), Binary))
830
831    def __invert__(self) -> Not:
832        return not_(self.copy())
def and_(self, *expressions, dialect=None, copy=True, **opts):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, copy=True, **opts):
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self, copy=True):
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy (bool): whether or not to copy this object.
Returns:

Not: the new condition.

def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
def between( self, low: Any, high: Any, copy=True, **opts) -> sqlglot.expressions.Between:
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
class Predicate(Condition):
835class Predicate(Condition):
836    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
839class DerivedTable(Expression):
840    @property
841    def alias_column_names(self):
842        table_alias = self.args.get("alias")
843        if not table_alias:
844            return []
845        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
846        return [c.name for c in column_list]
847
848    @property
849    def selects(self):
850        return self.this.selects if isinstance(self.this, Subqueryable) else []
851
852    @property
853    def named_selects(self):
854        return [select.output_name for select in self.selects]
class Unionable(Expression):
857class Unionable(Expression):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
877
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
897
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
919class UDTF(DerivedTable, Unionable):
920    @property
921    def selects(self):
922        alias = self.args.get("alias")
923        return alias.columns if alias else []
class Cache(Expression):
926class Cache(Expression):
927    arg_types = {
928        "with": False,
929        "this": True,
930        "lazy": False,
931        "options": False,
932        "expression": False,
933    }
class Uncache(Expression):
936class Uncache(Expression):
937    arg_types = {"this": True, "exists": False}
class Create(Expression):
940class Create(Expression):
941    arg_types = {
942        "with": False,
943        "this": True,
944        "kind": True,
945        "expression": False,
946        "exists": False,
947        "properties": False,
948        "replace": False,
949        "unique": False,
950        "indexes": False,
951        "no_schema_binding": False,
952        "begin": False,
953    }
class Describe(Expression):
956class Describe(Expression):
957    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
960class Pragma(Expression):
961    pass
class Set(Expression):
964class Set(Expression):
965    arg_types = {"expressions": False}
class SetItem(Expression):
968class SetItem(Expression):
969    arg_types = {
970        "this": False,
971        "expressions": False,
972        "kind": False,
973        "collate": False,  # MySQL SET NAMES statement
974        "global": False,
975    }
class Show(Expression):
978class Show(Expression):
979    arg_types = {
980        "this": True,
981        "target": False,
982        "offset": False,
983        "limit": False,
984        "like": False,
985        "where": False,
986        "db": False,
987        "full": False,
988        "mutex": False,
989        "query": False,
990        "channel": False,
991        "global": False,
992        "log": False,
993        "position": False,
994        "types": False,
995    }
class UserDefinedFunction(Expression):
998class UserDefinedFunction(Expression):
999    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1002class CharacterSet(Expression):
1003    arg_types = {"this": True, "default": False}
class With(Expression):
1006class With(Expression):
1007    arg_types = {"expressions": True, "recursive": False}
1008
1009    @property
1010    def recursive(self) -> bool:
1011        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1014class WithinGroup(Expression):
1015    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1018class CTE(DerivedTable):
1019    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1022class TableAlias(Expression):
1023    arg_types = {"this": False, "columns": False}
1024
1025    @property
1026    def columns(self):
1027        return self.args.get("columns") or []
class BitString(Condition):
1030class BitString(Condition):
1031    pass
class HexString(Condition):
1034class HexString(Condition):
1035    pass
class ByteString(Condition):
1038class ByteString(Condition):
1039    pass
class Column(Condition):
1042class Column(Condition):
1043    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1044
1045    @property
1046    def table(self) -> str:
1047        return self.text("table")
1048
1049    @property
1050    def db(self) -> str:
1051        return self.text("db")
1052
1053    @property
1054    def catalog(self) -> str:
1055        return self.text("catalog")
1056
1057    @property
1058    def output_name(self) -> str:
1059        return self.name
1060
1061    @property
1062    def parts(self) -> t.List[Identifier]:
1063        """Return the parts of a column in order catalog, db, table, name."""
1064        return [
1065            t.cast(Identifier, self.args[part])
1066            for part in ("catalog", "db", "table", "this")
1067            if self.args.get(part)
1068        ]
1069
1070    def to_dot(self) -> Dot:
1071        """Converts the column into a dot expression."""
1072        parts = self.parts
1073        parent = self.parent
1074
1075        while parent:
1076            if isinstance(parent, Dot):
1077                parts.append(parent.expression)
1078            parent = parent.parent
1079
1080        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1070    def to_dot(self) -> Dot:
1071        """Converts the column into a dot expression."""
1072        parts = self.parts
1073        parent = self.parent
1074
1075        while parent:
1076            if isinstance(parent, Dot):
1077                parts.append(parent.expression)
1078            parent = parent.parent
1079
1080        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1083class ColumnPosition(Expression):
1084    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1087class ColumnDef(Expression):
1088    arg_types = {
1089        "this": True,
1090        "kind": False,
1091        "constraints": False,
1092        "exists": False,
1093        "position": False,
1094    }
1095
1096    @property
1097    def constraints(self) -> t.List[ColumnConstraint]:
1098        return self.args.get("constraints") or []
class AlterColumn(Expression):
1101class AlterColumn(Expression):
1102    arg_types = {
1103        "this": True,
1104        "dtype": False,
1105        "collate": False,
1106        "using": False,
1107        "default": False,
1108        "drop": False,
1109    }
class RenameTable(Expression):
1112class RenameTable(Expression):
1113    pass
class SetTag(Expression):
1116class SetTag(Expression):
1117    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1120class Comment(Expression):
1121    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1125class MergeTreeTTLAction(Expression):
1126    arg_types = {
1127        "this": True,
1128        "delete": False,
1129        "recompress": False,
1130        "to_disk": False,
1131        "to_volume": False,
1132    }
class MergeTreeTTL(Expression):
1136class MergeTreeTTL(Expression):
1137    arg_types = {
1138        "expressions": True,
1139        "where": False,
1140        "group": False,
1141        "aggregates": False,
1142    }
class ColumnConstraint(Expression):
1145class ColumnConstraint(Expression):
1146    arg_types = {"this": False, "kind": True}
1147
1148    @property
1149    def kind(self) -> ColumnConstraintKind:
1150        return self.args["kind"]
class ColumnConstraintKind(Expression):
1153class ColumnConstraintKind(Expression):
1154    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1157class AutoIncrementColumnConstraint(ColumnConstraintKind):
1158    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1161class CaseSpecificColumnConstraint(ColumnConstraintKind):
1162    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1165class CharacterSetColumnConstraint(ColumnConstraintKind):
1166    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1169class CheckColumnConstraint(ColumnConstraintKind):
1170    pass
class CollateColumnConstraint(ColumnConstraintKind):
1173class CollateColumnConstraint(ColumnConstraintKind):
1174    pass
class CommentColumnConstraint(ColumnConstraintKind):
1177class CommentColumnConstraint(ColumnConstraintKind):
1178    pass
class CompressColumnConstraint(ColumnConstraintKind):
1181class CompressColumnConstraint(ColumnConstraintKind):
1182    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1185class DateFormatColumnConstraint(ColumnConstraintKind):
1186    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1189class DefaultColumnConstraint(ColumnConstraintKind):
1190    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1193class EncodeColumnConstraint(ColumnConstraintKind):
1194    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1197class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1198    # this: True -> ALWAYS, this: False -> BY DEFAULT
1199    arg_types = {
1200        "this": False,
1201        "on_null": False,
1202        "start": False,
1203        "increment": False,
1204        "minvalue": False,
1205        "maxvalue": False,
1206        "cycle": False,
1207    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1210class InlineLengthColumnConstraint(ColumnConstraintKind):
1211    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1214class NotNullColumnConstraint(ColumnConstraintKind):
1215    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1219class OnUpdateColumnConstraint(ColumnConstraintKind):
1220    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1223class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1224    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1227class TitleColumnConstraint(ColumnConstraintKind):
1228    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1231class UniqueColumnConstraint(ColumnConstraintKind):
1232    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1235class UppercaseColumnConstraint(ColumnConstraintKind):
1236    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1239class PathColumnConstraint(ColumnConstraintKind):
1240    pass
class Constraint(Expression):
1243class Constraint(Expression):
1244    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1247class Delete(Expression):
1248    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1249
1250    def delete(
1251        self,
1252        table: ExpOrStr,
1253        dialect: DialectType = None,
1254        copy: bool = True,
1255        **opts,
1256    ) -> Delete:
1257        """
1258        Create a DELETE expression or replace the table on an existing DELETE expression.
1259
1260        Example:
1261            >>> delete("tbl").sql()
1262            'DELETE FROM tbl'
1263
1264        Args:
1265            table: the table from which to delete.
1266            dialect: the dialect used to parse the input expression.
1267            copy: if `False`, modify this expression instance in-place.
1268            opts: other options to use to parse the input expressions.
1269
1270        Returns:
1271            Delete: the modified expression.
1272        """
1273        return _apply_builder(
1274            expression=table,
1275            instance=self,
1276            arg="this",
1277            dialect=dialect,
1278            into=Table,
1279            copy=copy,
1280            **opts,
1281        )
1282
1283    def where(
1284        self,
1285        *expressions: ExpOrStr,
1286        append: bool = True,
1287        dialect: DialectType = None,
1288        copy: bool = True,
1289        **opts,
1290    ) -> Delete:
1291        """
1292        Append to or set the WHERE expressions.
1293
1294        Example:
1295            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1296            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1297
1298        Args:
1299            *expressions: the SQL code strings to parse.
1300                If an `Expression` instance is passed, it will be used as-is.
1301                Multiple expressions are combined with an AND operator.
1302            append: if `True`, AND the new expressions to any existing expression.
1303                Otherwise, this resets the expression.
1304            dialect: the dialect used to parse the input expressions.
1305            copy: if `False`, modify this expression instance in-place.
1306            opts: other options to use to parse the input expressions.
1307
1308        Returns:
1309            Delete: the modified expression.
1310        """
1311        return _apply_conjunction_builder(
1312            *expressions,
1313            instance=self,
1314            arg="where",
1315            append=append,
1316            into=Where,
1317            dialect=dialect,
1318            copy=copy,
1319            **opts,
1320        )
1321
1322    def returning(
1323        self,
1324        expression: ExpOrStr,
1325        dialect: DialectType = None,
1326        copy: bool = True,
1327        **opts,
1328    ) -> Delete:
1329        """
1330        Set the RETURNING expression. Not supported by all dialects.
1331
1332        Example:
1333            >>> delete("tbl").returning("*", dialect="postgres").sql()
1334            'DELETE FROM tbl RETURNING *'
1335
1336        Args:
1337            expression: the SQL code strings to parse.
1338                If an `Expression` instance is passed, it will be used as-is.
1339            dialect: the dialect used to parse the input expressions.
1340            copy: if `False`, modify this expression instance in-place.
1341            opts: other options to use to parse the input expressions.
1342
1343        Returns:
1344            Delete: the modified expression.
1345        """
1346        return _apply_builder(
1347            expression=expression,
1348            instance=self,
1349            arg="returning",
1350            prefix="RETURNING",
1351            dialect=dialect,
1352            copy=copy,
1353            into=Returning,
1354            **opts,
1355        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1250    def delete(
1251        self,
1252        table: ExpOrStr,
1253        dialect: DialectType = None,
1254        copy: bool = True,
1255        **opts,
1256    ) -> Delete:
1257        """
1258        Create a DELETE expression or replace the table on an existing DELETE expression.
1259
1260        Example:
1261            >>> delete("tbl").sql()
1262            'DELETE FROM tbl'
1263
1264        Args:
1265            table: the table from which to delete.
1266            dialect: the dialect used to parse the input expression.
1267            copy: if `False`, modify this expression instance in-place.
1268            opts: other options to use to parse the input expressions.
1269
1270        Returns:
1271            Delete: the modified expression.
1272        """
1273        return _apply_builder(
1274            expression=table,
1275            instance=self,
1276            arg="this",
1277            dialect=dialect,
1278            into=Table,
1279            copy=copy,
1280            **opts,
1281        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1283    def where(
1284        self,
1285        *expressions: ExpOrStr,
1286        append: bool = True,
1287        dialect: DialectType = None,
1288        copy: bool = True,
1289        **opts,
1290    ) -> Delete:
1291        """
1292        Append to or set the WHERE expressions.
1293
1294        Example:
1295            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1296            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1297
1298        Args:
1299            *expressions: the SQL code strings to parse.
1300                If an `Expression` instance is passed, it will be used as-is.
1301                Multiple expressions are combined with an AND operator.
1302            append: if `True`, AND the new expressions to any existing expression.
1303                Otherwise, this resets the expression.
1304            dialect: the dialect used to parse the input expressions.
1305            copy: if `False`, modify this expression instance in-place.
1306            opts: other options to use to parse the input expressions.
1307
1308        Returns:
1309            Delete: the modified expression.
1310        """
1311        return _apply_conjunction_builder(
1312            *expressions,
1313            instance=self,
1314            arg="where",
1315            append=append,
1316            into=Where,
1317            dialect=dialect,
1318            copy=copy,
1319            **opts,
1320        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1322    def returning(
1323        self,
1324        expression: ExpOrStr,
1325        dialect: DialectType = None,
1326        copy: bool = True,
1327        **opts,
1328    ) -> Delete:
1329        """
1330        Set the RETURNING expression. Not supported by all dialects.
1331
1332        Example:
1333            >>> delete("tbl").returning("*", dialect="postgres").sql()
1334            'DELETE FROM tbl RETURNING *'
1335
1336        Args:
1337            expression: the SQL code strings to parse.
1338                If an `Expression` instance is passed, it will be used as-is.
1339            dialect: the dialect used to parse the input expressions.
1340            copy: if `False`, modify this expression instance in-place.
1341            opts: other options to use to parse the input expressions.
1342
1343        Returns:
1344            Delete: the modified expression.
1345        """
1346        return _apply_builder(
1347            expression=expression,
1348            instance=self,
1349            arg="returning",
1350            prefix="RETURNING",
1351            dialect=dialect,
1352            copy=copy,
1353            into=Returning,
1354            **opts,
1355        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1358class Drop(Expression):
1359    arg_types = {
1360        "this": False,
1361        "kind": False,
1362        "exists": False,
1363        "temporary": False,
1364        "materialized": False,
1365        "cascade": False,
1366        "constraints": False,
1367        "purge": False,
1368    }
class Filter(Expression):
1371class Filter(Expression):
1372    arg_types = {"this": True, "expression": True}
class Check(Expression):
1375class Check(Expression):
1376    pass
class Directory(Expression):
1379class Directory(Expression):
1380    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1381    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1384class ForeignKey(Expression):
1385    arg_types = {
1386        "expressions": True,
1387        "reference": False,
1388        "delete": False,
1389        "update": False,
1390    }
class PrimaryKey(Expression):
1393class PrimaryKey(Expression):
1394    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1397class Unique(Expression):
1398    arg_types = {"expressions": True}
class Into(Expression):
1403class Into(Expression):
1404    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1407class From(Expression):
1408    @property
1409    def name(self) -> str:
1410        return self.this.name
1411
1412    @property
1413    def alias_or_name(self) -> str:
1414        return self.this.alias_or_name
class Having(Expression):
1417class Having(Expression):
1418    pass
class Hint(Expression):
1421class Hint(Expression):
1422    arg_types = {"expressions": True}
class JoinHint(Expression):
1425class JoinHint(Expression):
1426    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1429class Identifier(Expression):
1430    arg_types = {"this": True, "quoted": False}
1431
1432    @property
1433    def quoted(self):
1434        return bool(self.args.get("quoted"))
1435
1436    @property
1437    def hashable_args(self) -> t.Any:
1438        if self.quoted and any(char.isupper() for char in self.this):
1439            return (self.this, self.quoted)
1440        return self.this.lower()
1441
1442    @property
1443    def output_name(self):
1444        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1447class Index(Expression):
1448    arg_types = {
1449        "this": False,
1450        "table": False,
1451        "where": False,
1452        "columns": False,
1453        "unique": False,
1454        "primary": False,
1455        "amp": False,  # teradata
1456    }
class Insert(Expression):
1459class Insert(Expression):
1460    arg_types = {
1461        "with": False,
1462        "this": True,
1463        "expression": False,
1464        "conflict": False,
1465        "returning": False,
1466        "overwrite": False,
1467        "exists": False,
1468        "partition": False,
1469        "alternative": False,
1470    }
class OnConflict(Expression):
1473class OnConflict(Expression):
1474    arg_types = {
1475        "duplicate": False,
1476        "expressions": False,
1477        "nothing": False,
1478        "key": False,
1479        "constraint": False,
1480    }
class Returning(Expression):
1483class Returning(Expression):
1484    arg_types = {"expressions": True}
class Introducer(Expression):
1488class Introducer(Expression):
1489    arg_types = {"this": True, "expression": True}
class National(Expression):
1493class National(Expression):
1494    pass
class LoadData(Expression):
1497class LoadData(Expression):
1498    arg_types = {
1499        "this": True,
1500        "local": False,
1501        "overwrite": False,
1502        "inpath": True,
1503        "partition": False,
1504        "input_format": False,
1505        "serde": False,
1506    }
class Partition(Expression):
1509class Partition(Expression):
1510    arg_types = {"expressions": True}
class Fetch(Expression):
1513class Fetch(Expression):
1514    arg_types = {
1515        "direction": False,
1516        "count": False,
1517        "percent": False,
1518        "with_ties": False,
1519    }
class Group(Expression):
1522class Group(Expression):
1523    arg_types = {
1524        "expressions": False,
1525        "grouping_sets": False,
1526        "cube": False,
1527        "rollup": False,
1528        "totals": False,
1529    }
class Lambda(Expression):
1532class Lambda(Expression):
1533    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1536class Limit(Expression):
1537    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1540class Literal(Condition):
1541    arg_types = {"this": True, "is_string": True}
1542
1543    @property
1544    def hashable_args(self) -> t.Any:
1545        return (self.this, self.args.get("is_string"))
1546
1547    @classmethod
1548    def number(cls, number) -> Literal:
1549        return cls(this=str(number), is_string=False)
1550
1551    @classmethod
1552    def string(cls, string) -> Literal:
1553        return cls(this=str(string), is_string=True)
1554
1555    @property
1556    def output_name(self):
1557        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1547    @classmethod
1548    def number(cls, number) -> Literal:
1549        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1551    @classmethod
1552    def string(cls, string) -> Literal:
1553        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1560class Join(Expression):
1561    arg_types = {
1562        "this": True,
1563        "on": False,
1564        "side": False,
1565        "kind": False,
1566        "using": False,
1567        "natural": False,
1568        "global": False,
1569        "hint": False,
1570    }
1571
1572    @property
1573    def kind(self):
1574        return self.text("kind").upper()
1575
1576    @property
1577    def side(self):
1578        return self.text("side").upper()
1579
1580    @property
1581    def hint(self):
1582        return self.text("hint").upper()
1583
1584    @property
1585    def alias_or_name(self):
1586        return self.this.alias_or_name
1587
1588    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1589        """
1590        Append to or set the ON expressions.
1591
1592        Example:
1593            >>> import sqlglot
1594            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1595            'JOIN x ON y = 1'
1596
1597        Args:
1598            *expressions (str | Expression): the SQL code strings to parse.
1599                If an `Expression` instance is passed, it will be used as-is.
1600                Multiple expressions are combined with an AND operator.
1601            append (bool): if `True`, AND the new expressions to any existing expression.
1602                Otherwise, this resets the expression.
1603            dialect (str): the dialect used to parse the input expressions.
1604            copy (bool): if `False`, modify this expression instance in-place.
1605            opts (kwargs): other options to use to parse the input expressions.
1606
1607        Returns:
1608            Join: the modified join expression.
1609        """
1610        join = _apply_conjunction_builder(
1611            *expressions,
1612            instance=self,
1613            arg="on",
1614            append=append,
1615            dialect=dialect,
1616            copy=copy,
1617            **opts,
1618        )
1619
1620        if join.kind == "CROSS":
1621            join.set("kind", None)
1622
1623        return join
1624
1625    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1626        """
1627        Append to or set the USING expressions.
1628
1629        Example:
1630            >>> import sqlglot
1631            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1632            'JOIN x USING (foo, bla)'
1633
1634        Args:
1635            *expressions (str | Expression): the SQL code strings to parse.
1636                If an `Expression` instance is passed, it will be used as-is.
1637            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1638                Otherwise, this resets the expression.
1639            dialect (str): the dialect used to parse the input expressions.
1640            copy (bool): if `False`, modify this expression instance in-place.
1641            opts (kwargs): other options to use to parse the input expressions.
1642
1643        Returns:
1644            Join: the modified join expression.
1645        """
1646        join = _apply_list_builder(
1647            *expressions,
1648            instance=self,
1649            arg="using",
1650            append=append,
1651            dialect=dialect,
1652            copy=copy,
1653            **opts,
1654        )
1655
1656        if join.kind == "CROSS":
1657            join.set("kind", None)
1658
1659        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1588    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1589        """
1590        Append to or set the ON expressions.
1591
1592        Example:
1593            >>> import sqlglot
1594            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1595            'JOIN x ON y = 1'
1596
1597        Args:
1598            *expressions (str | Expression): the SQL code strings to parse.
1599                If an `Expression` instance is passed, it will be used as-is.
1600                Multiple expressions are combined with an AND operator.
1601            append (bool): if `True`, AND the new expressions to any existing expression.
1602                Otherwise, this resets the expression.
1603            dialect (str): the dialect used to parse the input expressions.
1604            copy (bool): if `False`, modify this expression instance in-place.
1605            opts (kwargs): other options to use to parse the input expressions.
1606
1607        Returns:
1608            Join: the modified join expression.
1609        """
1610        join = _apply_conjunction_builder(
1611            *expressions,
1612            instance=self,
1613            arg="on",
1614            append=append,
1615            dialect=dialect,
1616            copy=copy,
1617            **opts,
1618        )
1619
1620        if join.kind == "CROSS":
1621            join.set("kind", None)
1622
1623        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1625    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1626        """
1627        Append to or set the USING expressions.
1628
1629        Example:
1630            >>> import sqlglot
1631            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1632            'JOIN x USING (foo, bla)'
1633
1634        Args:
1635            *expressions (str | Expression): the SQL code strings to parse.
1636                If an `Expression` instance is passed, it will be used as-is.
1637            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1638                Otherwise, this resets the expression.
1639            dialect (str): the dialect used to parse the input expressions.
1640            copy (bool): if `False`, modify this expression instance in-place.
1641            opts (kwargs): other options to use to parse the input expressions.
1642
1643        Returns:
1644            Join: the modified join expression.
1645        """
1646        join = _apply_list_builder(
1647            *expressions,
1648            instance=self,
1649            arg="using",
1650            append=append,
1651            dialect=dialect,
1652            copy=copy,
1653            **opts,
1654        )
1655
1656        if join.kind == "CROSS":
1657            join.set("kind", None)
1658
1659        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1662class Lateral(UDTF):
1663    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1666class MatchRecognize(Expression):
1667    arg_types = {
1668        "partition_by": False,
1669        "order": False,
1670        "measures": False,
1671        "rows": False,
1672        "after": False,
1673        "pattern": False,
1674        "define": False,
1675        "alias": False,
1676    }
class Final(Expression):
1681class Final(Expression):
1682    pass
class Offset(Expression):
1685class Offset(Expression):
1686    arg_types = {"this": False, "expression": True}
class Order(Expression):
1689class Order(Expression):
1690    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1695class Cluster(Order):
1696    pass
class Distribute(Order):
1699class Distribute(Order):
1700    pass
class Sort(Order):
1703class Sort(Order):
1704    pass
class Ordered(Expression):
1707class Ordered(Expression):
1708    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1711class Property(Expression):
1712    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1715class AfterJournalProperty(Property):
1716    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1719class AlgorithmProperty(Property):
1720    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1723class AutoIncrementProperty(Property):
1724    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1727class BlockCompressionProperty(Property):
1728    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1731class CharacterSetProperty(Property):
1732    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1735class ChecksumProperty(Property):
1736    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1739class CollateProperty(Property):
1740    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1743class DataBlocksizeProperty(Property):
1744    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1747class DefinerProperty(Property):
1748    arg_types = {"this": True}
class DistKeyProperty(Property):
1751class DistKeyProperty(Property):
1752    arg_types = {"this": True}
class DistStyleProperty(Property):
1755class DistStyleProperty(Property):
1756    arg_types = {"this": True}
class EngineProperty(Property):
1759class EngineProperty(Property):
1760    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1763class ExecuteAsProperty(Property):
1764    arg_types = {"this": True}
class ExternalProperty(Property):
1767class ExternalProperty(Property):
1768    arg_types = {"this": False}
class FallbackProperty(Property):
1771class FallbackProperty(Property):
1772    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1775class FileFormatProperty(Property):
1776    arg_types = {"this": True}
class FreespaceProperty(Property):
1779class FreespaceProperty(Property):
1780    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1783class InputOutputFormat(Expression):
1784    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1787class IsolatedLoadingProperty(Property):
1788    arg_types = {
1789        "no": True,
1790        "concurrent": True,
1791        "for_all": True,
1792        "for_insert": True,
1793        "for_none": True,
1794    }
class JournalProperty(Property):
1797class JournalProperty(Property):
1798    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1801class LanguageProperty(Property):
1802    arg_types = {"this": True}
class LikeProperty(Property):
1805class LikeProperty(Property):
1806    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1809class LocationProperty(Property):
1810    arg_types = {"this": True}
class LockingProperty(Property):
1813class LockingProperty(Property):
1814    arg_types = {
1815        "this": False,
1816        "kind": True,
1817        "for_or_in": True,
1818        "lock_type": True,
1819        "override": False,
1820    }
class LogProperty(Property):
1823class LogProperty(Property):
1824    arg_types = {"no": True}
class MaterializedProperty(Property):
1827class MaterializedProperty(Property):
1828    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1831class MergeBlockRatioProperty(Property):
1832    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1835class NoPrimaryIndexProperty(Property):
1836    arg_types = {"this": False}
class OnCommitProperty(Property):
1839class OnCommitProperty(Property):
1840    arg_type = {"this": False}
class PartitionedByProperty(Property):
1843class PartitionedByProperty(Property):
1844    arg_types = {"this": True}
class ReturnsProperty(Property):
1847class ReturnsProperty(Property):
1848    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1851class RowFormatProperty(Property):
1852    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1855class RowFormatDelimitedProperty(Property):
1856    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1857    arg_types = {
1858        "fields": False,
1859        "escaped": False,
1860        "collection_items": False,
1861        "map_keys": False,
1862        "lines": False,
1863        "null": False,
1864        "serde": False,
1865    }
class RowFormatSerdeProperty(Property):
1868class RowFormatSerdeProperty(Property):
1869    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1872class SchemaCommentProperty(Property):
1873    arg_types = {"this": True}
class SerdeProperties(Property):
1876class SerdeProperties(Property):
1877    arg_types = {"expressions": True}
class SetProperty(Property):
1880class SetProperty(Property):
1881    arg_types = {"multi": True}
class SettingsProperty(Property):
1884class SettingsProperty(Property):
1885    arg_types = {"expressions": True}
class SortKeyProperty(Property):
1888class SortKeyProperty(Property):
1889    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1892class SqlSecurityProperty(Property):
1893    arg_types = {"definer": True}
class StabilityProperty(Property):
1896class StabilityProperty(Property):
1897    arg_types = {"this": True}
class TableFormatProperty(Property):
1900class TableFormatProperty(Property):
1901    arg_types = {"this": True}
class TemporaryProperty(Property):
1904class TemporaryProperty(Property):
1905    arg_types = {"global_": True}
class TransientProperty(Property):
1908class TransientProperty(Property):
1909    arg_types = {"this": False}
class VolatileProperty(Property):
1912class VolatileProperty(Property):
1913    arg_types = {"this": False}
class WithDataProperty(Property):
1916class WithDataProperty(Property):
1917    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1920class WithJournalTableProperty(Property):
1921    arg_types = {"this": True}
class Properties(Expression):
1924class Properties(Expression):
1925    arg_types = {"expressions": True}
1926
1927    NAME_TO_PROPERTY = {
1928        "ALGORITHM": AlgorithmProperty,
1929        "AUTO_INCREMENT": AutoIncrementProperty,
1930        "CHARACTER SET": CharacterSetProperty,
1931        "COLLATE": CollateProperty,
1932        "COMMENT": SchemaCommentProperty,
1933        "DEFINER": DefinerProperty,
1934        "DISTKEY": DistKeyProperty,
1935        "DISTSTYLE": DistStyleProperty,
1936        "ENGINE": EngineProperty,
1937        "EXECUTE AS": ExecuteAsProperty,
1938        "FORMAT": FileFormatProperty,
1939        "LANGUAGE": LanguageProperty,
1940        "LOCATION": LocationProperty,
1941        "PARTITIONED_BY": PartitionedByProperty,
1942        "RETURNS": ReturnsProperty,
1943        "ROW_FORMAT": RowFormatProperty,
1944        "SORTKEY": SortKeyProperty,
1945        "TABLE_FORMAT": TableFormatProperty,
1946    }
1947
1948    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1949
1950    # CREATE property locations
1951    # Form: schema specified
1952    #   create [POST_CREATE]
1953    #     table a [POST_NAME]
1954    #     (b int) [POST_SCHEMA]
1955    #     with ([POST_WITH])
1956    #     index (b) [POST_INDEX]
1957    #
1958    # Form: alias selection
1959    #   create [POST_CREATE]
1960    #     table a [POST_NAME]
1961    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1962    #     index (c) [POST_INDEX]
1963    class Location(AutoName):
1964        POST_CREATE = auto()
1965        POST_NAME = auto()
1966        POST_SCHEMA = auto()
1967        POST_WITH = auto()
1968        POST_ALIAS = auto()
1969        POST_EXPRESSION = auto()
1970        POST_INDEX = auto()
1971        UNSUPPORTED = auto()
1972
1973    @classmethod
1974    def from_dict(cls, properties_dict) -> Properties:
1975        expressions = []
1976        for key, value in properties_dict.items():
1977            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1978            if property_cls:
1979                expressions.append(property_cls(this=convert(value)))
1980            else:
1981                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1982
1983        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1973    @classmethod
1974    def from_dict(cls, properties_dict) -> Properties:
1975        expressions = []
1976        for key, value in properties_dict.items():
1977            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1978            if property_cls:
1979                expressions.append(property_cls(this=convert(value)))
1980            else:
1981                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1982
1983        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1963    class Location(AutoName):
1964        POST_CREATE = auto()
1965        POST_NAME = auto()
1966        POST_SCHEMA = auto()
1967        POST_WITH = auto()
1968        POST_ALIAS = auto()
1969        POST_EXPRESSION = auto()
1970        POST_INDEX = auto()
1971        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1986class Qualify(Expression):
1987    pass
class Return(Expression):
1991class Return(Expression):
1992    pass
class Reference(Expression):
1995class Reference(Expression):
1996    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1999class Tuple(Expression):
2000    arg_types = {"expressions": False}
2001
2002    def isin(
2003        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2004    ) -> In:
2005        return In(
2006            this=_maybe_copy(self, copy),
2007            expressions=[convert(e, copy=copy) for e in expressions],
2008            query=maybe_parse(query, copy=copy, **opts) if query else None,
2009        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
2002    def isin(
2003        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2004    ) -> In:
2005        return In(
2006            this=_maybe_copy(self, copy),
2007            expressions=[convert(e, copy=copy) for e in expressions],
2008            query=maybe_parse(query, copy=copy, **opts) if query else None,
2009        )
class Subqueryable(Unionable):
2012class Subqueryable(Unionable):
2013    def subquery(self, alias=None, copy=True) -> Subquery:
2014        """
2015        Convert this expression to an aliased expression that can be used as a Subquery.
2016
2017        Example:
2018            >>> subquery = Select().select("x").from_("tbl").subquery()
2019            >>> Select().select("x").from_(subquery).sql()
2020            'SELECT x FROM (SELECT x FROM tbl)'
2021
2022        Args:
2023            alias (str | Identifier): an optional alias for the subquery
2024            copy (bool): if `False`, modify this expression instance in-place.
2025
2026        Returns:
2027            Alias: the subquery
2028        """
2029        instance = _maybe_copy(self, copy)
2030        return Subquery(
2031            this=instance,
2032            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2033        )
2034
2035    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2036        raise NotImplementedError
2037
2038    @property
2039    def ctes(self):
2040        with_ = self.args.get("with")
2041        if not with_:
2042            return []
2043        return with_.expressions
2044
2045    @property
2046    def selects(self):
2047        raise NotImplementedError("Subqueryable objects must implement `selects`")
2048
2049    @property
2050    def named_selects(self):
2051        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2052
2053    def with_(
2054        self,
2055        alias,
2056        as_,
2057        recursive=None,
2058        append=True,
2059        dialect=None,
2060        copy=True,
2061        **opts,
2062    ):
2063        """
2064        Append to or set the common table expressions.
2065
2066        Example:
2067            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2068            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2069
2070        Args:
2071            alias (str | Expression): the SQL code string to parse as the table name.
2072                If an `Expression` instance is passed, this is used as-is.
2073            as_ (str | Expression): the SQL code string to parse as the table expression.
2074                If an `Expression` instance is passed, it will be used as-is.
2075            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2076            append (bool): if `True`, add to any existing expressions.
2077                Otherwise, this resets the expressions.
2078            dialect (str): the dialect used to parse the input expression.
2079            copy (bool): if `False`, modify this expression instance in-place.
2080            opts (kwargs): other options to use to parse the input expressions.
2081
2082        Returns:
2083            Select: the modified expression.
2084        """
2085        alias_expression = maybe_parse(
2086            alias,
2087            dialect=dialect,
2088            into=TableAlias,
2089            **opts,
2090        )
2091        as_expression = maybe_parse(
2092            as_,
2093            dialect=dialect,
2094            **opts,
2095        )
2096        cte = CTE(
2097            this=as_expression,
2098            alias=alias_expression,
2099        )
2100        return _apply_child_list_builder(
2101            cte,
2102            instance=self,
2103            arg="with",
2104            append=append,
2105            copy=copy,
2106            into=With,
2107            properties={"recursive": recursive or False},
2108        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
2013    def subquery(self, alias=None, copy=True) -> Subquery:
2014        """
2015        Convert this expression to an aliased expression that can be used as a Subquery.
2016
2017        Example:
2018            >>> subquery = Select().select("x").from_("tbl").subquery()
2019            >>> Select().select("x").from_(subquery).sql()
2020            'SELECT x FROM (SELECT x FROM tbl)'
2021
2022        Args:
2023            alias (str | Identifier): an optional alias for the subquery
2024            copy (bool): if `False`, modify this expression instance in-place.
2025
2026        Returns:
2027            Alias: the subquery
2028        """
2029        instance = _maybe_copy(self, copy)
2030        return Subquery(
2031            this=instance,
2032            alias=TableAlias(this=to_identifier(alias)) if alias else None,
2033        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2035    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2036        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
2053    def with_(
2054        self,
2055        alias,
2056        as_,
2057        recursive=None,
2058        append=True,
2059        dialect=None,
2060        copy=True,
2061        **opts,
2062    ):
2063        """
2064        Append to or set the common table expressions.
2065
2066        Example:
2067            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2068            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2069
2070        Args:
2071            alias (str | Expression): the SQL code string to parse as the table name.
2072                If an `Expression` instance is passed, this is used as-is.
2073            as_ (str | Expression): the SQL code string to parse as the table expression.
2074                If an `Expression` instance is passed, it will be used as-is.
2075            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
2076            append (bool): if `True`, add to any existing expressions.
2077                Otherwise, this resets the expressions.
2078            dialect (str): the dialect used to parse the input expression.
2079            copy (bool): if `False`, modify this expression instance in-place.
2080            opts (kwargs): other options to use to parse the input expressions.
2081
2082        Returns:
2083            Select: the modified expression.
2084        """
2085        alias_expression = maybe_parse(
2086            alias,
2087            dialect=dialect,
2088            into=TableAlias,
2089            **opts,
2090        )
2091        as_expression = maybe_parse(
2092            as_,
2093            dialect=dialect,
2094            **opts,
2095        )
2096        cte = CTE(
2097            this=as_expression,
2098            alias=alias_expression,
2099        )
2100        return _apply_child_list_builder(
2101            cte,
2102            instance=self,
2103            arg="with",
2104            append=append,
2105            copy=copy,
2106            into=With,
2107            properties={"recursive": recursive or False},
2108        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
2134class Table(Expression):
2135    arg_types = {
2136        "this": True,
2137        "alias": False,
2138        "db": False,
2139        "catalog": False,
2140        "laterals": False,
2141        "joins": False,
2142        "pivots": False,
2143        "hints": False,
2144        "system_time": False,
2145    }
2146
2147    @property
2148    def db(self) -> str:
2149        return self.text("db")
2150
2151    @property
2152    def catalog(self) -> str:
2153        return self.text("catalog")
2154
2155    @property
2156    def parts(self) -> t.List[Identifier]:
2157        """Return the parts of a column in order catalog, db, table."""
2158        return [
2159            t.cast(Identifier, self.args[part])
2160            for part in ("catalog", "db", "this")
2161            if self.args.get(part)
2162        ]

Return the parts of a column in order catalog, db, table.

class SystemTime(Expression):
2166class SystemTime(Expression):
2167    arg_types = {
2168        "this": False,
2169        "expression": False,
2170        "kind": True,
2171    }
class Union(Subqueryable):
2174class Union(Subqueryable):
2175    arg_types = {
2176        "with": False,
2177        "this": True,
2178        "expression": True,
2179        "distinct": False,
2180        **QUERY_MODIFIERS,
2181    }
2182
2183    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2184        """
2185        Set the LIMIT expression.
2186
2187        Example:
2188            >>> select("1").union(select("1")).limit(1).sql()
2189            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2190
2191        Args:
2192            expression (str | int | Expression): the SQL code string to parse.
2193                This can also be an integer.
2194                If a `Limit` instance is passed, this is used as-is.
2195                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2196            dialect (str): the dialect used to parse the input expression.
2197            copy (bool): if `False`, modify this expression instance in-place.
2198            opts (kwargs): other options to use to parse the input expressions.
2199
2200        Returns:
2201            Select: The limited subqueryable.
2202        """
2203        return (
2204            select("*")
2205            .from_(self.subquery(alias="_l_0", copy=copy))
2206            .limit(expression, dialect=dialect, copy=False, **opts)
2207        )
2208
2209    def select(
2210        self,
2211        *expressions: ExpOrStr,
2212        append: bool = True,
2213        dialect: DialectType = None,
2214        copy: bool = True,
2215        **opts,
2216    ) -> Union:
2217        """Append to or set the SELECT of the union recursively.
2218
2219        Example:
2220            >>> from sqlglot import parse_one
2221            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2222            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2223
2224        Args:
2225            *expressions: the SQL code strings to parse.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            append: if `True`, add to any existing expressions.
2228                Otherwise, this resets the expressions.
2229            dialect: the dialect used to parse the input expressions.
2230            copy: if `False`, modify this expression instance in-place.
2231            opts: other options to use to parse the input expressions.
2232
2233        Returns:
2234            Union: the modified expression.
2235        """
2236        this = self.copy() if copy else self
2237        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2238        this.expression.unnest().select(
2239            *expressions, append=append, dialect=dialect, copy=False, **opts
2240        )
2241        return this
2242
2243    @property
2244    def named_selects(self):
2245        return self.this.unnest().named_selects
2246
2247    @property
2248    def is_star(self) -> bool:
2249        return self.this.is_star or self.expression.is_star
2250
2251    @property
2252    def selects(self):
2253        return self.this.unnest().selects
2254
2255    @property
2256    def left(self):
2257        return self.this
2258
2259    @property
2260    def right(self):
2261        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2183    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2184        """
2185        Set the LIMIT expression.
2186
2187        Example:
2188            >>> select("1").union(select("1")).limit(1).sql()
2189            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2190
2191        Args:
2192            expression (str | int | Expression): the SQL code string to parse.
2193                This can also be an integer.
2194                If a `Limit` instance is passed, this is used as-is.
2195                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2196            dialect (str): the dialect used to parse the input expression.
2197            copy (bool): if `False`, modify this expression instance in-place.
2198            opts (kwargs): other options to use to parse the input expressions.
2199
2200        Returns:
2201            Select: The limited subqueryable.
2202        """
2203        return (
2204            select("*")
2205            .from_(self.subquery(alias="_l_0", copy=copy))
2206            .limit(expression, dialect=dialect, copy=False, **opts)
2207        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2209    def select(
2210        self,
2211        *expressions: ExpOrStr,
2212        append: bool = True,
2213        dialect: DialectType = None,
2214        copy: bool = True,
2215        **opts,
2216    ) -> Union:
2217        """Append to or set the SELECT of the union recursively.
2218
2219        Example:
2220            >>> from sqlglot import parse_one
2221            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2222            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2223
2224        Args:
2225            *expressions: the SQL code strings to parse.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            append: if `True`, add to any existing expressions.
2228                Otherwise, this resets the expressions.
2229            dialect: the dialect used to parse the input expressions.
2230            copy: if `False`, modify this expression instance in-place.
2231            opts: other options to use to parse the input expressions.
2232
2233        Returns:
2234            Union: the modified expression.
2235        """
2236        this = self.copy() if copy else self
2237        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2238        this.expression.unnest().select(
2239            *expressions, append=append, dialect=dialect, copy=False, **opts
2240        )
2241        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2264class Except(Union):
2265    pass
class Intersect(Union):
2268class Intersect(Union):
2269    pass
class Unnest(UDTF):
2272class Unnest(UDTF):
2273    arg_types = {
2274        "expressions": True,
2275        "ordinality": False,
2276        "alias": False,
2277        "offset": False,
2278    }
class Update(Expression):
2281class Update(Expression):
2282    arg_types = {
2283        "with": False,
2284        "this": False,
2285        "expressions": True,
2286        "from": False,
2287        "where": False,
2288        "returning": False,
2289    }
class Values(UDTF):
2292class Values(UDTF):
2293    arg_types = {
2294        "expressions": True,
2295        "ordinality": False,
2296        "alias": False,
2297    }
class Var(Expression):
2300class Var(Expression):
2301    pass
class Schema(Expression):
2304class Schema(Expression):
2305    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2310class Lock(Expression):
2311    arg_types = {"update": True}
class Select(Subqueryable):
2314class Select(Subqueryable):
2315    arg_types = {
2316        "with": False,
2317        "kind": False,
2318        "expressions": False,
2319        "hint": False,
2320        "distinct": False,
2321        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2322        "value": False,
2323        "into": False,
2324        "from": False,
2325        **QUERY_MODIFIERS,
2326    }
2327
2328    def from_(
2329        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2330    ) -> Select:
2331        """
2332        Set the FROM expression.
2333
2334        Example:
2335            >>> Select().from_("tbl").select("x").sql()
2336            'SELECT x FROM tbl'
2337
2338        Args:
2339            expression : the SQL code strings to parse.
2340                If a `From` instance is passed, this is used as-is.
2341                If another `Expression` instance is passed, it will be wrapped in a `From`.
2342            dialect: the dialect used to parse the input expression.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            Select: the modified expression.
2348        """
2349        return _apply_builder(
2350            expression=expression,
2351            instance=self,
2352            arg="from",
2353            into=From,
2354            prefix="FROM",
2355            dialect=dialect,
2356            copy=copy,
2357            **opts,
2358        )
2359
2360    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2361        """
2362        Set the GROUP BY expression.
2363
2364        Example:
2365            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2366            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2367
2368        Args:
2369            *expressions (str | Expression): the SQL code strings to parse.
2370                If a `Group` instance is passed, this is used as-is.
2371                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2372                If nothing is passed in then a group by is not applied to the expression
2373            append (bool): if `True`, add to any existing expressions.
2374                Otherwise, this flattens all the `Group` expression into a single expression.
2375            dialect (str): the dialect used to parse the input expression.
2376            copy (bool): if `False`, modify this expression instance in-place.
2377            opts (kwargs): other options to use to parse the input expressions.
2378
2379        Returns:
2380            Select: the modified expression.
2381        """
2382        if not expressions:
2383            return self if not copy else self.copy()
2384        return _apply_child_list_builder(
2385            *expressions,
2386            instance=self,
2387            arg="group",
2388            append=append,
2389            copy=copy,
2390            prefix="GROUP BY",
2391            into=Group,
2392            dialect=dialect,
2393            **opts,
2394        )
2395
2396    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2397        """
2398        Set the ORDER BY expression.
2399
2400        Example:
2401            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2402            'SELECT x FROM tbl ORDER BY x DESC'
2403
2404        Args:
2405            *expressions (str | Expression): the SQL code strings to parse.
2406                If a `Group` instance is passed, this is used as-is.
2407                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2408            append (bool): if `True`, add to any existing expressions.
2409                Otherwise, this flattens all the `Order` expression into a single expression.
2410            dialect (str): the dialect used to parse the input expression.
2411            copy (bool): if `False`, modify this expression instance in-place.
2412            opts (kwargs): other options to use to parse the input expressions.
2413
2414        Returns:
2415            Select: the modified expression.
2416        """
2417        return _apply_child_list_builder(
2418            *expressions,
2419            instance=self,
2420            arg="order",
2421            append=append,
2422            copy=copy,
2423            prefix="ORDER BY",
2424            into=Order,
2425            dialect=dialect,
2426            **opts,
2427        )
2428
2429    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2430        """
2431        Set the SORT BY expression.
2432
2433        Example:
2434            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2435            'SELECT x FROM tbl SORT BY x DESC'
2436
2437        Args:
2438            *expressions (str | Expression): the SQL code strings to parse.
2439                If a `Group` instance is passed, this is used as-is.
2440                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2441            append (bool): if `True`, add to any existing expressions.
2442                Otherwise, this flattens all the `Order` expression into a single expression.
2443            dialect (str): the dialect used to parse the input expression.
2444            copy (bool): if `False`, modify this expression instance in-place.
2445            opts (kwargs): other options to use to parse the input expressions.
2446
2447        Returns:
2448            Select: the modified expression.
2449        """
2450        return _apply_child_list_builder(
2451            *expressions,
2452            instance=self,
2453            arg="sort",
2454            append=append,
2455            copy=copy,
2456            prefix="SORT BY",
2457            into=Sort,
2458            dialect=dialect,
2459            **opts,
2460        )
2461
2462    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2463        """
2464        Set the CLUSTER BY expression.
2465
2466        Example:
2467            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2468            'SELECT x FROM tbl CLUSTER BY x DESC'
2469
2470        Args:
2471            *expressions (str | Expression): the SQL code strings to parse.
2472                If a `Group` instance is passed, this is used as-is.
2473                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2474            append (bool): if `True`, add to any existing expressions.
2475                Otherwise, this flattens all the `Order` expression into a single expression.
2476            dialect (str): the dialect used to parse the input expression.
2477            copy (bool): if `False`, modify this expression instance in-place.
2478            opts (kwargs): other options to use to parse the input expressions.
2479
2480        Returns:
2481            Select: the modified expression.
2482        """
2483        return _apply_child_list_builder(
2484            *expressions,
2485            instance=self,
2486            arg="cluster",
2487            append=append,
2488            copy=copy,
2489            prefix="CLUSTER BY",
2490            into=Cluster,
2491            dialect=dialect,
2492            **opts,
2493        )
2494
2495    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2496        """
2497        Set the LIMIT expression.
2498
2499        Example:
2500            >>> Select().from_("tbl").select("x").limit(10).sql()
2501            'SELECT x FROM tbl LIMIT 10'
2502
2503        Args:
2504            expression (str | int | Expression): the SQL code string to parse.
2505                This can also be an integer.
2506                If a `Limit` instance is passed, this is used as-is.
2507                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2508            dialect (str): the dialect used to parse the input expression.
2509            copy (bool): if `False`, modify this expression instance in-place.
2510            opts (kwargs): other options to use to parse the input expressions.
2511
2512        Returns:
2513            Select: the modified expression.
2514        """
2515        return _apply_builder(
2516            expression=expression,
2517            instance=self,
2518            arg="limit",
2519            into=Limit,
2520            prefix="LIMIT",
2521            dialect=dialect,
2522            copy=copy,
2523            **opts,
2524        )
2525
2526    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2527        """
2528        Set the OFFSET expression.
2529
2530        Example:
2531            >>> Select().from_("tbl").select("x").offset(10).sql()
2532            'SELECT x FROM tbl OFFSET 10'
2533
2534        Args:
2535            expression (str | int | Expression): the SQL code string to parse.
2536                This can also be an integer.
2537                If a `Offset` instance is passed, this is used as-is.
2538                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2539            dialect (str): the dialect used to parse the input expression.
2540            copy (bool): if `False`, modify this expression instance in-place.
2541            opts (kwargs): other options to use to parse the input expressions.
2542
2543        Returns:
2544            Select: the modified expression.
2545        """
2546        return _apply_builder(
2547            expression=expression,
2548            instance=self,
2549            arg="offset",
2550            into=Offset,
2551            prefix="OFFSET",
2552            dialect=dialect,
2553            copy=copy,
2554            **opts,
2555        )
2556
2557    def select(
2558        self,
2559        *expressions: ExpOrStr,
2560        append: bool = True,
2561        dialect: DialectType = None,
2562        copy: bool = True,
2563        **opts,
2564    ) -> Select:
2565        """
2566        Append to or set the SELECT expressions.
2567
2568        Example:
2569            >>> Select().select("x", "y").sql()
2570            'SELECT x, y'
2571
2572        Args:
2573            *expressions: the SQL code strings to parse.
2574                If an `Expression` instance is passed, it will be used as-is.
2575            append: if `True`, add to any existing expressions.
2576                Otherwise, this resets the expressions.
2577            dialect: the dialect used to parse the input expressions.
2578            copy: if `False`, modify this expression instance in-place.
2579            opts: other options to use to parse the input expressions.
2580
2581        Returns:
2582            Select: the modified expression.
2583        """
2584        return _apply_list_builder(
2585            *expressions,
2586            instance=self,
2587            arg="expressions",
2588            append=append,
2589            dialect=dialect,
2590            copy=copy,
2591            **opts,
2592        )
2593
2594    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2595        """
2596        Append to or set the LATERAL expressions.
2597
2598        Example:
2599            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2600            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2601
2602        Args:
2603            *expressions (str | Expression): the SQL code strings to parse.
2604                If an `Expression` instance is passed, it will be used as-is.
2605            append (bool): if `True`, add to any existing expressions.
2606                Otherwise, this resets the expressions.
2607            dialect (str): the dialect used to parse the input expressions.
2608            copy (bool): if `False`, modify this expression instance in-place.
2609            opts (kwargs): other options to use to parse the input expressions.
2610
2611        Returns:
2612            Select: the modified expression.
2613        """
2614        return _apply_list_builder(
2615            *expressions,
2616            instance=self,
2617            arg="laterals",
2618            append=append,
2619            into=Lateral,
2620            prefix="LATERAL VIEW",
2621            dialect=dialect,
2622            copy=copy,
2623            **opts,
2624        )
2625
2626    def join(
2627        self,
2628        expression,
2629        on=None,
2630        using=None,
2631        append=True,
2632        join_type=None,
2633        join_alias=None,
2634        dialect=None,
2635        copy=True,
2636        **opts,
2637    ) -> Select:
2638        """
2639        Append to or set the JOIN expressions.
2640
2641        Example:
2642            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2643            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2644
2645            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2646            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2647
2648            Use `join_type` to change the type of join:
2649
2650            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2651            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2652
2653        Args:
2654            expression (str | Expression): the SQL code string to parse.
2655                If an `Expression` instance is passed, it will be used as-is.
2656            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2657                If an `Expression` instance is passed, it will be used as-is.
2658            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2659                If an `Expression` instance is passed, it will be used as-is.
2660            append (bool): if `True`, add to any existing expressions.
2661                Otherwise, this resets the expressions.
2662            join_type (str): If set, alter the parsed join type
2663            dialect (str): the dialect used to parse the input expressions.
2664            copy (bool): if `False`, modify this expression instance in-place.
2665            opts (kwargs): other options to use to parse the input expressions.
2666
2667        Returns:
2668            Select: the modified expression.
2669        """
2670        parse_args = {"dialect": dialect, **opts}
2671
2672        try:
2673            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2674        except ParseError:
2675            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2676
2677        join = expression if isinstance(expression, Join) else Join(this=expression)
2678
2679        if isinstance(join.this, Select):
2680            join.this.replace(join.this.subquery())
2681
2682        if join_type:
2683            natural: t.Optional[Token]
2684            side: t.Optional[Token]
2685            kind: t.Optional[Token]
2686
2687            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2688
2689            if natural:
2690                join.set("natural", True)
2691            if side:
2692                join.set("side", side.text)
2693            if kind:
2694                join.set("kind", kind.text)
2695
2696        if on:
2697            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2698            join.set("on", on)
2699
2700        if using:
2701            join = _apply_list_builder(
2702                *ensure_collection(using),
2703                instance=join,
2704                arg="using",
2705                append=append,
2706                copy=copy,
2707                **opts,
2708            )
2709
2710        if join_alias:
2711            join.set("this", alias_(join.this, join_alias, table=True))
2712        return _apply_list_builder(
2713            join,
2714            instance=self,
2715            arg="joins",
2716            append=append,
2717            copy=copy,
2718            **opts,
2719        )
2720
2721    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2722        """
2723        Append to or set the WHERE expressions.
2724
2725        Example:
2726            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2727            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2728
2729        Args:
2730            *expressions (str | Expression): the SQL code strings to parse.
2731                If an `Expression` instance is passed, it will be used as-is.
2732                Multiple expressions are combined with an AND operator.
2733            append (bool): if `True`, AND the new expressions to any existing expression.
2734                Otherwise, this resets the expression.
2735            dialect (str): the dialect used to parse the input expressions.
2736            copy (bool): if `False`, modify this expression instance in-place.
2737            opts (kwargs): other options to use to parse the input expressions.
2738
2739        Returns:
2740            Select: the modified expression.
2741        """
2742        return _apply_conjunction_builder(
2743            *expressions,
2744            instance=self,
2745            arg="where",
2746            append=append,
2747            into=Where,
2748            dialect=dialect,
2749            copy=copy,
2750            **opts,
2751        )
2752
2753    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2754        """
2755        Append to or set the HAVING expressions.
2756
2757        Example:
2758            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2759            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2760
2761        Args:
2762            *expressions (str | Expression): the SQL code strings to parse.
2763                If an `Expression` instance is passed, it will be used as-is.
2764                Multiple expressions are combined with an AND operator.
2765            append (bool): if `True`, AND the new expressions to any existing expression.
2766                Otherwise, this resets the expression.
2767            dialect (str): the dialect used to parse the input expressions.
2768            copy (bool): if `False`, modify this expression instance in-place.
2769            opts (kwargs): other options to use to parse the input expressions.
2770
2771        Returns:
2772            Select: the modified expression.
2773        """
2774        return _apply_conjunction_builder(
2775            *expressions,
2776            instance=self,
2777            arg="having",
2778            append=append,
2779            into=Having,
2780            dialect=dialect,
2781            copy=copy,
2782            **opts,
2783        )
2784
2785    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2786        return _apply_list_builder(
2787            *expressions,
2788            instance=self,
2789            arg="windows",
2790            append=append,
2791            into=Window,
2792            dialect=dialect,
2793            copy=copy,
2794            **opts,
2795        )
2796
2797    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2798        return _apply_conjunction_builder(
2799            *expressions,
2800            instance=self,
2801            arg="qualify",
2802            append=append,
2803            into=Qualify,
2804            dialect=dialect,
2805            copy=copy,
2806            **opts,
2807        )
2808
2809    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2810        """
2811        Set the OFFSET expression.
2812
2813        Example:
2814            >>> Select().from_("tbl").select("x").distinct().sql()
2815            'SELECT DISTINCT x FROM tbl'
2816
2817        Args:
2818            ons: the expressions to distinct on
2819            distinct: whether the Select should be distinct
2820            copy: if `False`, modify this expression instance in-place.
2821
2822        Returns:
2823            Select: the modified expression.
2824        """
2825        instance = _maybe_copy(self, copy)
2826        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2827        instance.set("distinct", Distinct(on=on) if distinct else None)
2828        return instance
2829
2830    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2831        """
2832        Convert this expression to a CREATE TABLE AS statement.
2833
2834        Example:
2835            >>> Select().select("*").from_("tbl").ctas("x").sql()
2836            'CREATE TABLE x AS SELECT * FROM tbl'
2837
2838        Args:
2839            table (str | Expression): the SQL code string to parse as the table name.
2840                If another `Expression` instance is passed, it will be used as-is.
2841            properties (dict): an optional mapping of table properties
2842            dialect (str): the dialect used to parse the input table.
2843            copy (bool): if `False`, modify this expression instance in-place.
2844            opts (kwargs): other options to use to parse the input table.
2845
2846        Returns:
2847            Create: the CREATE TABLE AS expression
2848        """
2849        instance = _maybe_copy(self, copy)
2850        table_expression = maybe_parse(
2851            table,
2852            into=Table,
2853            dialect=dialect,
2854            **opts,
2855        )
2856        properties_expression = None
2857        if properties:
2858            properties_expression = Properties.from_dict(properties)
2859
2860        return Create(
2861            this=table_expression,
2862            kind="table",
2863            expression=instance,
2864            properties=properties_expression,
2865        )
2866
2867    def lock(self, update: bool = True, copy: bool = True) -> Select:
2868        """
2869        Set the locking read mode for this expression.
2870
2871        Examples:
2872            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2873            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2874
2875            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2876            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2877
2878        Args:
2879            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2880            copy: if `False`, modify this expression instance in-place.
2881
2882        Returns:
2883            The modified expression.
2884        """
2885
2886        inst = _maybe_copy(self, copy)
2887        inst.set("lock", Lock(update=update))
2888
2889        return inst
2890
2891    @property
2892    def named_selects(self) -> t.List[str]:
2893        return [e.output_name for e in self.expressions if e.alias_or_name]
2894
2895    @property
2896    def is_star(self) -> bool:
2897        return any(expression.is_star for expression in self.expressions)
2898
2899    @property
2900    def selects(self) -> t.List[Expression]:
2901        return self.expressions
def from_( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2328    def from_(
2329        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2330    ) -> Select:
2331        """
2332        Set the FROM expression.
2333
2334        Example:
2335            >>> Select().from_("tbl").select("x").sql()
2336            'SELECT x FROM tbl'
2337
2338        Args:
2339            expression : the SQL code strings to parse.
2340                If a `From` instance is passed, this is used as-is.
2341                If another `Expression` instance is passed, it will be wrapped in a `From`.
2342            dialect: the dialect used to parse the input expression.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            Select: the modified expression.
2348        """
2349        return _apply_builder(
2350            expression=expression,
2351            instance=self,
2352            arg="from",
2353            into=From,
2354            prefix="FROM",
2355            dialect=dialect,
2356            copy=copy,
2357            **opts,
2358        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2360    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2361        """
2362        Set the GROUP BY expression.
2363
2364        Example:
2365            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2366            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2367
2368        Args:
2369            *expressions (str | Expression): the SQL code strings to parse.
2370                If a `Group` instance is passed, this is used as-is.
2371                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2372                If nothing is passed in then a group by is not applied to the expression
2373            append (bool): if `True`, add to any existing expressions.
2374                Otherwise, this flattens all the `Group` expression into a single expression.
2375            dialect (str): the dialect used to parse the input expression.
2376            copy (bool): if `False`, modify this expression instance in-place.
2377            opts (kwargs): other options to use to parse the input expressions.
2378
2379        Returns:
2380            Select: the modified expression.
2381        """
2382        if not expressions:
2383            return self if not copy else self.copy()
2384        return _apply_child_list_builder(
2385            *expressions,
2386            instance=self,
2387            arg="group",
2388            append=append,
2389            copy=copy,
2390            prefix="GROUP BY",
2391            into=Group,
2392            dialect=dialect,
2393            **opts,
2394        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2396    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2397        """
2398        Set the ORDER BY expression.
2399
2400        Example:
2401            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2402            'SELECT x FROM tbl ORDER BY x DESC'
2403
2404        Args:
2405            *expressions (str | Expression): the SQL code strings to parse.
2406                If a `Group` instance is passed, this is used as-is.
2407                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2408            append (bool): if `True`, add to any existing expressions.
2409                Otherwise, this flattens all the `Order` expression into a single expression.
2410            dialect (str): the dialect used to parse the input expression.
2411            copy (bool): if `False`, modify this expression instance in-place.
2412            opts (kwargs): other options to use to parse the input expressions.
2413
2414        Returns:
2415            Select: the modified expression.
2416        """
2417        return _apply_child_list_builder(
2418            *expressions,
2419            instance=self,
2420            arg="order",
2421            append=append,
2422            copy=copy,
2423            prefix="ORDER BY",
2424            into=Order,
2425            dialect=dialect,
2426            **opts,
2427        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2429    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2430        """
2431        Set the SORT BY expression.
2432
2433        Example:
2434            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2435            'SELECT x FROM tbl SORT BY x DESC'
2436
2437        Args:
2438            *expressions (str | Expression): the SQL code strings to parse.
2439                If a `Group` instance is passed, this is used as-is.
2440                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2441            append (bool): if `True`, add to any existing expressions.
2442                Otherwise, this flattens all the `Order` expression into a single expression.
2443            dialect (str): the dialect used to parse the input expression.
2444            copy (bool): if `False`, modify this expression instance in-place.
2445            opts (kwargs): other options to use to parse the input expressions.
2446
2447        Returns:
2448            Select: the modified expression.
2449        """
2450        return _apply_child_list_builder(
2451            *expressions,
2452            instance=self,
2453            arg="sort",
2454            append=append,
2455            copy=copy,
2456            prefix="SORT BY",
2457            into=Sort,
2458            dialect=dialect,
2459            **opts,
2460        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2462    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2463        """
2464        Set the CLUSTER BY expression.
2465
2466        Example:
2467            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2468            'SELECT x FROM tbl CLUSTER BY x DESC'
2469
2470        Args:
2471            *expressions (str | Expression): the SQL code strings to parse.
2472                If a `Group` instance is passed, this is used as-is.
2473                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2474            append (bool): if `True`, add to any existing expressions.
2475                Otherwise, this flattens all the `Order` expression into a single expression.
2476            dialect (str): the dialect used to parse the input expression.
2477            copy (bool): if `False`, modify this expression instance in-place.
2478            opts (kwargs): other options to use to parse the input expressions.
2479
2480        Returns:
2481            Select: the modified expression.
2482        """
2483        return _apply_child_list_builder(
2484            *expressions,
2485            instance=self,
2486            arg="cluster",
2487            append=append,
2488            copy=copy,
2489            prefix="CLUSTER BY",
2490            into=Cluster,
2491            dialect=dialect,
2492            **opts,
2493        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2495    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2496        """
2497        Set the LIMIT expression.
2498
2499        Example:
2500            >>> Select().from_("tbl").select("x").limit(10).sql()
2501            'SELECT x FROM tbl LIMIT 10'
2502
2503        Args:
2504            expression (str | int | Expression): the SQL code string to parse.
2505                This can also be an integer.
2506                If a `Limit` instance is passed, this is used as-is.
2507                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2508            dialect (str): the dialect used to parse the input expression.
2509            copy (bool): if `False`, modify this expression instance in-place.
2510            opts (kwargs): other options to use to parse the input expressions.
2511
2512        Returns:
2513            Select: the modified expression.
2514        """
2515        return _apply_builder(
2516            expression=expression,
2517            instance=self,
2518            arg="limit",
2519            into=Limit,
2520            prefix="LIMIT",
2521            dialect=dialect,
2522            copy=copy,
2523            **opts,
2524        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2526    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2527        """
2528        Set the OFFSET expression.
2529
2530        Example:
2531            >>> Select().from_("tbl").select("x").offset(10).sql()
2532            'SELECT x FROM tbl OFFSET 10'
2533
2534        Args:
2535            expression (str | int | Expression): the SQL code string to parse.
2536                This can also be an integer.
2537                If a `Offset` instance is passed, this is used as-is.
2538                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2539            dialect (str): the dialect used to parse the input expression.
2540            copy (bool): if `False`, modify this expression instance in-place.
2541            opts (kwargs): other options to use to parse the input expressions.
2542
2543        Returns:
2544            Select: the modified expression.
2545        """
2546        return _apply_builder(
2547            expression=expression,
2548            instance=self,
2549            arg="offset",
2550            into=Offset,
2551            prefix="OFFSET",
2552            dialect=dialect,
2553            copy=copy,
2554            **opts,
2555        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2557    def select(
2558        self,
2559        *expressions: ExpOrStr,
2560        append: bool = True,
2561        dialect: DialectType = None,
2562        copy: bool = True,
2563        **opts,
2564    ) -> Select:
2565        """
2566        Append to or set the SELECT expressions.
2567
2568        Example:
2569            >>> Select().select("x", "y").sql()
2570            'SELECT x, y'
2571
2572        Args:
2573            *expressions: the SQL code strings to parse.
2574                If an `Expression` instance is passed, it will be used as-is.
2575            append: if `True`, add to any existing expressions.
2576                Otherwise, this resets the expressions.
2577            dialect: the dialect used to parse the input expressions.
2578            copy: if `False`, modify this expression instance in-place.
2579            opts: other options to use to parse the input expressions.
2580
2581        Returns:
2582            Select: the modified expression.
2583        """
2584        return _apply_list_builder(
2585            *expressions,
2586            instance=self,
2587            arg="expressions",
2588            append=append,
2589            dialect=dialect,
2590            copy=copy,
2591            **opts,
2592        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2594    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2595        """
2596        Append to or set the LATERAL expressions.
2597
2598        Example:
2599            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2600            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2601
2602        Args:
2603            *expressions (str | Expression): the SQL code strings to parse.
2604                If an `Expression` instance is passed, it will be used as-is.
2605            append (bool): if `True`, add to any existing expressions.
2606                Otherwise, this resets the expressions.
2607            dialect (str): the dialect used to parse the input expressions.
2608            copy (bool): if `False`, modify this expression instance in-place.
2609            opts (kwargs): other options to use to parse the input expressions.
2610
2611        Returns:
2612            Select: the modified expression.
2613        """
2614        return _apply_list_builder(
2615            *expressions,
2616            instance=self,
2617            arg="laterals",
2618            append=append,
2619            into=Lateral,
2620            prefix="LATERAL VIEW",
2621            dialect=dialect,
2622            copy=copy,
2623            **opts,
2624        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2626    def join(
2627        self,
2628        expression,
2629        on=None,
2630        using=None,
2631        append=True,
2632        join_type=None,
2633        join_alias=None,
2634        dialect=None,
2635        copy=True,
2636        **opts,
2637    ) -> Select:
2638        """
2639        Append to or set the JOIN expressions.
2640
2641        Example:
2642            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2643            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2644
2645            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2646            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2647
2648            Use `join_type` to change the type of join:
2649
2650            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2651            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2652
2653        Args:
2654            expression (str | Expression): the SQL code string to parse.
2655                If an `Expression` instance is passed, it will be used as-is.
2656            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2657                If an `Expression` instance is passed, it will be used as-is.
2658            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2659                If an `Expression` instance is passed, it will be used as-is.
2660            append (bool): if `True`, add to any existing expressions.
2661                Otherwise, this resets the expressions.
2662            join_type (str): If set, alter the parsed join type
2663            dialect (str): the dialect used to parse the input expressions.
2664            copy (bool): if `False`, modify this expression instance in-place.
2665            opts (kwargs): other options to use to parse the input expressions.
2666
2667        Returns:
2668            Select: the modified expression.
2669        """
2670        parse_args = {"dialect": dialect, **opts}
2671
2672        try:
2673            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2674        except ParseError:
2675            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2676
2677        join = expression if isinstance(expression, Join) else Join(this=expression)
2678
2679        if isinstance(join.this, Select):
2680            join.this.replace(join.this.subquery())
2681
2682        if join_type:
2683            natural: t.Optional[Token]
2684            side: t.Optional[Token]
2685            kind: t.Optional[Token]
2686
2687            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2688
2689            if natural:
2690                join.set("natural", True)
2691            if side:
2692                join.set("side", side.text)
2693            if kind:
2694                join.set("kind", kind.text)
2695
2696        if on:
2697            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2698            join.set("on", on)
2699
2700        if using:
2701            join = _apply_list_builder(
2702                *ensure_collection(using),
2703                instance=join,
2704                arg="using",
2705                append=append,
2706                copy=copy,
2707                **opts,
2708            )
2709
2710        if join_alias:
2711            join.set("this", alias_(join.this, join_alias, table=True))
2712        return _apply_list_builder(
2713            join,
2714            instance=self,
2715            arg="joins",
2716            append=append,
2717            copy=copy,
2718            **opts,
2719        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2721    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2722        """
2723        Append to or set the WHERE expressions.
2724
2725        Example:
2726            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2727            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2728
2729        Args:
2730            *expressions (str | Expression): the SQL code strings to parse.
2731                If an `Expression` instance is passed, it will be used as-is.
2732                Multiple expressions are combined with an AND operator.
2733            append (bool): if `True`, AND the new expressions to any existing expression.
2734                Otherwise, this resets the expression.
2735            dialect (str): the dialect used to parse the input expressions.
2736            copy (bool): if `False`, modify this expression instance in-place.
2737            opts (kwargs): other options to use to parse the input expressions.
2738
2739        Returns:
2740            Select: the modified expression.
2741        """
2742        return _apply_conjunction_builder(
2743            *expressions,
2744            instance=self,
2745            arg="where",
2746            append=append,
2747            into=Where,
2748            dialect=dialect,
2749            copy=copy,
2750            **opts,
2751        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2753    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2754        """
2755        Append to or set the HAVING expressions.
2756
2757        Example:
2758            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2759            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2760
2761        Args:
2762            *expressions (str | Expression): the SQL code strings to parse.
2763                If an `Expression` instance is passed, it will be used as-is.
2764                Multiple expressions are combined with an AND operator.
2765            append (bool): if `True`, AND the new expressions to any existing expression.
2766                Otherwise, this resets the expression.
2767            dialect (str): the dialect used to parse the input expressions.
2768            copy (bool): if `False`, modify this expression instance in-place.
2769            opts (kwargs): other options to use to parse the input expressions.
2770
2771        Returns:
2772            Select: the modified expression.
2773        """
2774        return _apply_conjunction_builder(
2775            *expressions,
2776            instance=self,
2777            arg="having",
2778            append=append,
2779            into=Having,
2780            dialect=dialect,
2781            copy=copy,
2782            **opts,
2783        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2785    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2786        return _apply_list_builder(
2787            *expressions,
2788            instance=self,
2789            arg="windows",
2790            append=append,
2791            into=Window,
2792            dialect=dialect,
2793            copy=copy,
2794            **opts,
2795        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2797    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2798        return _apply_conjunction_builder(
2799            *expressions,
2800            instance=self,
2801            arg="qualify",
2802            append=append,
2803            into=Qualify,
2804            dialect=dialect,
2805            copy=copy,
2806            **opts,
2807        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2809    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2810        """
2811        Set the OFFSET expression.
2812
2813        Example:
2814            >>> Select().from_("tbl").select("x").distinct().sql()
2815            'SELECT DISTINCT x FROM tbl'
2816
2817        Args:
2818            ons: the expressions to distinct on
2819            distinct: whether the Select should be distinct
2820            copy: if `False`, modify this expression instance in-place.
2821
2822        Returns:
2823            Select: the modified expression.
2824        """
2825        instance = _maybe_copy(self, copy)
2826        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2827        instance.set("distinct", Distinct(on=on) if distinct else None)
2828        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2830    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2831        """
2832        Convert this expression to a CREATE TABLE AS statement.
2833
2834        Example:
2835            >>> Select().select("*").from_("tbl").ctas("x").sql()
2836            'CREATE TABLE x AS SELECT * FROM tbl'
2837
2838        Args:
2839            table (str | Expression): the SQL code string to parse as the table name.
2840                If another `Expression` instance is passed, it will be used as-is.
2841            properties (dict): an optional mapping of table properties
2842            dialect (str): the dialect used to parse the input table.
2843            copy (bool): if `False`, modify this expression instance in-place.
2844            opts (kwargs): other options to use to parse the input table.
2845
2846        Returns:
2847            Create: the CREATE TABLE AS expression
2848        """
2849        instance = _maybe_copy(self, copy)
2850        table_expression = maybe_parse(
2851            table,
2852            into=Table,
2853            dialect=dialect,
2854            **opts,
2855        )
2856        properties_expression = None
2857        if properties:
2858            properties_expression = Properties.from_dict(properties)
2859
2860        return Create(
2861            this=table_expression,
2862            kind="table",
2863            expression=instance,
2864            properties=properties_expression,
2865        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2867    def lock(self, update: bool = True, copy: bool = True) -> Select:
2868        """
2869        Set the locking read mode for this expression.
2870
2871        Examples:
2872            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2873            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2874
2875            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2876            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2877
2878        Args:
2879            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2880            copy: if `False`, modify this expression instance in-place.
2881
2882        Returns:
2883            The modified expression.
2884        """
2885
2886        inst = _maybe_copy(self, copy)
2887        inst.set("lock", Lock(update=update))
2888
2889        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2904class Subquery(DerivedTable, Unionable):
2905    arg_types = {
2906        "this": True,
2907        "alias": False,
2908        "with": False,
2909        **QUERY_MODIFIERS,
2910    }
2911
2912    def unnest(self):
2913        """
2914        Returns the first non subquery.
2915        """
2916        expression = self
2917        while isinstance(expression, Subquery):
2918            expression = expression.this
2919        return expression
2920
2921    @property
2922    def is_star(self) -> bool:
2923        return self.this.is_star
2924
2925    @property
2926    def output_name(self):
2927        return self.alias
def unnest(self):
2912    def unnest(self):
2913        """
2914        Returns the first non subquery.
2915        """
2916        expression = self
2917        while isinstance(expression, Subquery):
2918            expression = expression.this
2919        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2930class TableSample(Expression):
2931    arg_types = {
2932        "this": False,
2933        "method": False,
2934        "bucket_numerator": False,
2935        "bucket_denominator": False,
2936        "bucket_field": False,
2937        "percent": False,
2938        "rows": False,
2939        "size": False,
2940        "seed": False,
2941        "kind": False,
2942    }
class Tag(Expression):
2945class Tag(Expression):
2946    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2947
2948    arg_types = {
2949        "this": False,
2950        "prefix": False,
2951        "postfix": False,
2952    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2955class Pivot(Expression):
2956    arg_types = {
2957        "this": False,
2958        "alias": False,
2959        "expressions": True,
2960        "field": True,
2961        "unpivot": True,
2962        "columns": False,
2963    }
class Window(Expression):
2966class Window(Expression):
2967    arg_types = {
2968        "this": True,
2969        "partition_by": False,
2970        "order": False,
2971        "spec": False,
2972        "alias": False,
2973        "over": False,
2974        "first": False,
2975    }
class WindowSpec(Expression):
2978class WindowSpec(Expression):
2979    arg_types = {
2980        "kind": False,
2981        "start": False,
2982        "start_side": False,
2983        "end": False,
2984        "end_side": False,
2985    }
class Where(Expression):
2988class Where(Expression):
2989    pass
class Star(Expression):
2992class Star(Expression):
2993    arg_types = {"except": False, "replace": False}
2994
2995    @property
2996    def name(self) -> str:
2997        return "*"
2998
2999    @property
3000    def output_name(self):
3001        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
3004class Parameter(Expression):
3005    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3008class SessionParameter(Expression):
3009    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3012class Placeholder(Expression):
3013    arg_types = {"this": False}
class Null(Condition):
3016class Null(Condition):
3017    arg_types: t.Dict[str, t.Any] = {}
3018
3019    @property
3020    def name(self) -> str:
3021        return "NULL"
class Boolean(Condition):
3024class Boolean(Condition):
3025    pass
class DataTypeSize(Expression):
3028class DataTypeSize(Expression):
3029    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3032class DataType(Expression):
3033    arg_types = {
3034        "this": True,
3035        "expressions": False,
3036        "nested": False,
3037        "values": False,
3038        "prefix": False,
3039    }
3040
3041    class Type(AutoName):
3042        CHAR = auto()
3043        NCHAR = auto()
3044        VARCHAR = auto()
3045        NVARCHAR = auto()
3046        TEXT = auto()
3047        MEDIUMTEXT = auto()
3048        LONGTEXT = auto()
3049        MEDIUMBLOB = auto()
3050        LONGBLOB = auto()
3051        BINARY = auto()
3052        VARBINARY = auto()
3053        INT = auto()
3054        UINT = auto()
3055        TINYINT = auto()
3056        UTINYINT = auto()
3057        SMALLINT = auto()
3058        USMALLINT = auto()
3059        BIGINT = auto()
3060        UBIGINT = auto()
3061        INT128 = auto()
3062        UINT128 = auto()
3063        INT256 = auto()
3064        UINT256 = auto()
3065        FLOAT = auto()
3066        DOUBLE = auto()
3067        DECIMAL = auto()
3068        BIGDECIMAL = auto()
3069        BIT = auto()
3070        BOOLEAN = auto()
3071        JSON = auto()
3072        JSONB = auto()
3073        INTERVAL = auto()
3074        TIME = auto()
3075        TIMESTAMP = auto()
3076        TIMESTAMPTZ = auto()
3077        TIMESTAMPLTZ = auto()
3078        DATE = auto()
3079        DATETIME = auto()
3080        DATETIME64 = auto()
3081        ARRAY = auto()
3082        MAP = auto()
3083        UUID = auto()
3084        GEOGRAPHY = auto()
3085        GEOMETRY = auto()
3086        STRUCT = auto()
3087        NULLABLE = auto()
3088        HLLSKETCH = auto()
3089        HSTORE = auto()
3090        SUPER = auto()
3091        SERIAL = auto()
3092        SMALLSERIAL = auto()
3093        BIGSERIAL = auto()
3094        XML = auto()
3095        UNIQUEIDENTIFIER = auto()
3096        MONEY = auto()
3097        SMALLMONEY = auto()
3098        ROWVERSION = auto()
3099        IMAGE = auto()
3100        VARIANT = auto()
3101        OBJECT = auto()
3102        INET = auto()
3103        NULL = auto()
3104        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3105
3106    TEXT_TYPES = {
3107        Type.CHAR,
3108        Type.NCHAR,
3109        Type.VARCHAR,
3110        Type.NVARCHAR,
3111        Type.TEXT,
3112    }
3113
3114    INTEGER_TYPES = {
3115        Type.INT,
3116        Type.TINYINT,
3117        Type.SMALLINT,
3118        Type.BIGINT,
3119        Type.INT128,
3120        Type.INT256,
3121    }
3122
3123    FLOAT_TYPES = {
3124        Type.FLOAT,
3125        Type.DOUBLE,
3126    }
3127
3128    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3129
3130    TEMPORAL_TYPES = {
3131        Type.TIMESTAMP,
3132        Type.TIMESTAMPTZ,
3133        Type.TIMESTAMPLTZ,
3134        Type.DATE,
3135        Type.DATETIME,
3136        Type.DATETIME64,
3137    }
3138
3139    @classmethod
3140    def build(
3141        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3142    ) -> DataType:
3143        from sqlglot import parse_one
3144
3145        if isinstance(dtype, str):
3146            if dtype.upper() in cls.Type.__members__:
3147                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3148            else:
3149                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3150            if data_type_exp is None:
3151                raise ValueError(f"Unparsable data type value: {dtype}")
3152        elif isinstance(dtype, DataType.Type):
3153            data_type_exp = DataType(this=dtype)
3154        elif isinstance(dtype, DataType):
3155            return dtype
3156        else:
3157            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3158        return DataType(**{**data_type_exp.args, **kwargs})
3159
3160    def is_type(self, dtype: DataType.Type) -> bool:
3161        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3139    @classmethod
3140    def build(
3141        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3142    ) -> DataType:
3143        from sqlglot import parse_one
3144
3145        if isinstance(dtype, str):
3146            if dtype.upper() in cls.Type.__members__:
3147                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3148            else:
3149                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3150            if data_type_exp is None:
3151                raise ValueError(f"Unparsable data type value: {dtype}")
3152        elif isinstance(dtype, DataType.Type):
3153            data_type_exp = DataType(this=dtype)
3154        elif isinstance(dtype, DataType):
3155            return dtype
3156        else:
3157            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3158        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3160    def is_type(self, dtype: DataType.Type) -> bool:
3161        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3041    class Type(AutoName):
3042        CHAR = auto()
3043        NCHAR = auto()
3044        VARCHAR = auto()
3045        NVARCHAR = auto()
3046        TEXT = auto()
3047        MEDIUMTEXT = auto()
3048        LONGTEXT = auto()
3049        MEDIUMBLOB = auto()
3050        LONGBLOB = auto()
3051        BINARY = auto()
3052        VARBINARY = auto()
3053        INT = auto()
3054        UINT = auto()
3055        TINYINT = auto()
3056        UTINYINT = auto()
3057        SMALLINT = auto()
3058        USMALLINT = auto()
3059        BIGINT = auto()
3060        UBIGINT = auto()
3061        INT128 = auto()
3062        UINT128 = auto()
3063        INT256 = auto()
3064        UINT256 = auto()
3065        FLOAT = auto()
3066        DOUBLE = auto()
3067        DECIMAL = auto()
3068        BIGDECIMAL = auto()
3069        BIT = auto()
3070        BOOLEAN = auto()
3071        JSON = auto()
3072        JSONB = auto()
3073        INTERVAL = auto()
3074        TIME = auto()
3075        TIMESTAMP = auto()
3076        TIMESTAMPTZ = auto()
3077        TIMESTAMPLTZ = auto()
3078        DATE = auto()
3079        DATETIME = auto()
3080        DATETIME64 = auto()
3081        ARRAY = auto()
3082        MAP = auto()
3083        UUID = auto()
3084        GEOGRAPHY = auto()
3085        GEOMETRY = auto()
3086        STRUCT = auto()
3087        NULLABLE = auto()
3088        HLLSKETCH = auto()
3089        HSTORE = auto()
3090        SUPER = auto()
3091        SERIAL = auto()
3092        SMALLSERIAL = auto()
3093        BIGSERIAL = auto()
3094        XML = auto()
3095        UNIQUEIDENTIFIER = auto()
3096        MONEY = auto()
3097        SMALLMONEY = auto()
3098        ROWVERSION = auto()
3099        IMAGE = auto()
3100        VARIANT = auto()
3101        OBJECT = auto()
3102        INET = auto()
3103        NULL = auto()
3104        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
INT128 = <Type.INT128: 'INT128'>
UINT128 = <Type.UINT128: 'UINT128'>
INT256 = <Type.INT256: 'INT256'>
UINT256 = <Type.UINT256: 'UINT256'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3165class PseudoType(Expression):
3166    pass
class SubqueryPredicate(Predicate):
3170class SubqueryPredicate(Predicate):
3171    pass
class All(SubqueryPredicate):
3174class All(SubqueryPredicate):
3175    pass
class Any(SubqueryPredicate):
3178class Any(SubqueryPredicate):
3179    pass
class Exists(SubqueryPredicate):
3182class Exists(SubqueryPredicate):
3183    pass
class Command(Expression):
3188class Command(Expression):
3189    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3192class Transaction(Expression):
3193    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3196class Commit(Expression):
3197    arg_types = {"chain": False}
class Rollback(Expression):
3200class Rollback(Expression):
3201    arg_types = {"savepoint": False}
class AlterTable(Expression):
3204class AlterTable(Expression):
3205    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3208class AddConstraint(Expression):
3209    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3212class DropPartition(Expression):
3213    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3217class Binary(Condition):
3218    arg_types = {"this": True, "expression": True}
3219
3220    @property
3221    def left(self):
3222        return self.this
3223
3224    @property
3225    def right(self):
3226        return self.expression
class Add(Binary):
3229class Add(Binary):
3230    pass
class Connector(Binary):
3233class Connector(Binary):
3234    pass
class And(Connector):
3237class And(Connector):
3238    pass
class Or(Connector):
3241class Or(Connector):
3242    pass
class BitwiseAnd(Binary):
3245class BitwiseAnd(Binary):
3246    pass
class BitwiseLeftShift(Binary):
3249class BitwiseLeftShift(Binary):
3250    pass
class BitwiseOr(Binary):
3253class BitwiseOr(Binary):
3254    pass
class BitwiseRightShift(Binary):
3257class BitwiseRightShift(Binary):
3258    pass
class BitwiseXor(Binary):
3261class BitwiseXor(Binary):
3262    pass
class Div(Binary):
3265class Div(Binary):
3266    pass
class Overlaps(Binary):
3269class Overlaps(Binary):
3270    pass
class Dot(Binary):
3273class Dot(Binary):
3274    @property
3275    def name(self) -> str:
3276        return self.expression.name
3277
3278    @classmethod
3279    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3280        """Build a Dot object with a sequence of expressions."""
3281        if len(expressions) < 2:
3282            raise ValueError(f"Dot requires >= 2 expressions.")
3283
3284        a, b, *expressions = expressions
3285        dot = Dot(this=a, expression=b)
3286
3287        for expression in expressions:
3288            dot = Dot(this=dot, expression=expression)
3289
3290        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3278    @classmethod
3279    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3280        """Build a Dot object with a sequence of expressions."""
3281        if len(expressions) < 2:
3282            raise ValueError(f"Dot requires >= 2 expressions.")
3283
3284        a, b, *expressions = expressions
3285        dot = Dot(this=a, expression=b)
3286
3287        for expression in expressions:
3288            dot = Dot(this=dot, expression=expression)
3289
3290        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3293class DPipe(Binary):
3294    pass
class EQ(Binary, Predicate):
3297class EQ(Binary, Predicate):
3298    pass
class NullSafeEQ(Binary, Predicate):
3301class NullSafeEQ(Binary, Predicate):
3302    pass
class NullSafeNEQ(Binary, Predicate):
3305class NullSafeNEQ(Binary, Predicate):
3306    pass
class Distance(Binary):
3309class Distance(Binary):
3310    pass
class Escape(Binary):
3313class Escape(Binary):
3314    pass
class Glob(Binary, Predicate):
3317class Glob(Binary, Predicate):
3318    pass
class GT(Binary, Predicate):
3321class GT(Binary, Predicate):
3322    pass
class GTE(Binary, Predicate):
3325class GTE(Binary, Predicate):
3326    pass
class ILike(Binary, Predicate):
3329class ILike(Binary, Predicate):
3330    pass
class ILikeAny(Binary, Predicate):
3333class ILikeAny(Binary, Predicate):
3334    pass
class IntDiv(Binary):
3337class IntDiv(Binary):
3338    pass
class Is(Binary, Predicate):
3341class Is(Binary, Predicate):
3342    pass
class Kwarg(Binary):
3345class Kwarg(Binary):
3346    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3349class Like(Binary, Predicate):
3350    pass
class LikeAny(Binary, Predicate):
3353class LikeAny(Binary, Predicate):
3354    pass
class LT(Binary, Predicate):
3357class LT(Binary, Predicate):
3358    pass
class LTE(Binary, Predicate):
3361class LTE(Binary, Predicate):
3362    pass
class Mod(Binary):
3365class Mod(Binary):
3366    pass
class Mul(Binary):
3369class Mul(Binary):
3370    pass
class NEQ(Binary, Predicate):
3373class NEQ(Binary, Predicate):
3374    pass
class SimilarTo(Binary, Predicate):
3377class SimilarTo(Binary, Predicate):
3378    pass
class Slice(Binary):
3381class Slice(Binary):
3382    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3385class Sub(Binary):
3386    pass
class ArrayOverlaps(Binary):
3389class ArrayOverlaps(Binary):
3390    pass
class Unary(Condition):
3395class Unary(Condition):
3396    pass
class BitwiseNot(Unary):
3399class BitwiseNot(Unary):
3400    pass
class Not(Unary):
3403class Not(Unary):
3404    pass
class Paren(Unary):
3407class Paren(Unary):
3408    arg_types = {"this": True, "with": False}
class Neg(Unary):
3411class Neg(Unary):
3412    pass
class Alias(Expression):
3415class Alias(Expression):
3416    arg_types = {"this": True, "alias": False}
3417
3418    @property
3419    def output_name(self):
3420        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3423class Aliases(Expression):
3424    arg_types = {"this": True, "expressions": True}
3425
3426    @property
3427    def aliases(self):
3428        return self.expressions
class AtTimeZone(Expression):
3431class AtTimeZone(Expression):
3432    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3435class Between(Predicate):
3436    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3439class Bracket(Condition):
3440    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3443class Distinct(Expression):
3444    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3447class In(Predicate):
3448    arg_types = {
3449        "this": True,
3450        "expressions": False,
3451        "query": False,
3452        "unnest": False,
3453        "field": False,
3454        "is_global": False,
3455    }
class TimeUnit(Expression):
3458class TimeUnit(Expression):
3459    """Automatically converts unit arg into a var."""
3460
3461    arg_types = {"unit": False}
3462
3463    def __init__(self, **args):
3464        unit = args.get("unit")
3465        if isinstance(unit, (Column, Literal)):
3466            args["unit"] = Var(this=unit.name)
3467        elif isinstance(unit, Week):
3468            unit.set("this", Var(this=unit.this.name))
3469        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3463    def __init__(self, **args):
3464        unit = args.get("unit")
3465        if isinstance(unit, (Column, Literal)):
3466            args["unit"] = Var(this=unit.name)
3467        elif isinstance(unit, Week):
3468            unit.set("this", Var(this=unit.this.name))
3469        super().__init__(**args)
class Interval(TimeUnit):
3472class Interval(TimeUnit):
3473    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3476class IgnoreNulls(Expression):
3477    pass
class RespectNulls(Expression):
3480class RespectNulls(Expression):
3481    pass
class Func(Condition):
3485class Func(Condition):
3486    """
3487    The base class for all function expressions.
3488
3489    Attributes:
3490        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3491            treated as a variable length argument and the argument's value will be stored as a list.
3492        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3493            for this function expression. These values are used to map this node to a name during parsing
3494            as well as to provide the function's name during SQL string generation. By default the SQL
3495            name is set to the expression's class name transformed to snake case.
3496    """
3497
3498    is_var_len_args = False
3499
3500    @classmethod
3501    def from_arg_list(cls, args):
3502        if cls.is_var_len_args:
3503            all_arg_keys = list(cls.arg_types)
3504            # If this function supports variable length argument treat the last argument as such.
3505            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3506            num_non_var = len(non_var_len_arg_keys)
3507
3508            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3509            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3510        else:
3511            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3512
3513        return cls(**args_dict)
3514
3515    @classmethod
3516    def sql_names(cls):
3517        if cls is Func:
3518            raise NotImplementedError(
3519                "SQL name is only supported by concrete function implementations"
3520            )
3521        if "_sql_names" not in cls.__dict__:
3522            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3523        return cls._sql_names
3524
3525    @classmethod
3526    def sql_name(cls):
3527        return cls.sql_names()[0]
3528
3529    @classmethod
3530    def default_parser_mappings(cls):
3531        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3500    @classmethod
3501    def from_arg_list(cls, args):
3502        if cls.is_var_len_args:
3503            all_arg_keys = list(cls.arg_types)
3504            # If this function supports variable length argument treat the last argument as such.
3505            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3506            num_non_var = len(non_var_len_arg_keys)
3507
3508            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3509            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3510        else:
3511            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3512
3513        return cls(**args_dict)
@classmethod
def sql_names(cls):
3515    @classmethod
3516    def sql_names(cls):
3517        if cls is Func:
3518            raise NotImplementedError(
3519                "SQL name is only supported by concrete function implementations"
3520            )
3521        if "_sql_names" not in cls.__dict__:
3522            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3523        return cls._sql_names
@classmethod
def sql_name(cls):
3525    @classmethod
3526    def sql_name(cls):
3527        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3529    @classmethod
3530    def default_parser_mappings(cls):
3531        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3534class AggFunc(Func):
3535    pass
class ParameterizedAgg(AggFunc):
3538class ParameterizedAgg(AggFunc):
3539    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3542class Abs(Func):
3543    pass
class Anonymous(Func):
3546class Anonymous(Func):
3547    arg_types = {"this": True, "expressions": False}
3548    is_var_len_args = True
class Hll(AggFunc):
3553class Hll(AggFunc):
3554    arg_types = {"this": True, "expressions": False}
3555    is_var_len_args = True
class ApproxDistinct(AggFunc):
3558class ApproxDistinct(AggFunc):
3559    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3562class Array(Func):
3563    arg_types = {"expressions": False}
3564    is_var_len_args = True
class ToChar(Func):
3568class ToChar(Func):
3569    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3572class GenerateSeries(Func):
3573    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3576class ArrayAgg(AggFunc):
3577    pass
class ArrayAll(Func):
3580class ArrayAll(Func):
3581    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3584class ArrayAny(Func):
3585    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3588class ArrayConcat(Func):
3589    arg_types = {"this": True, "expressions": False}
3590    is_var_len_args = True
class ArrayContains(Binary, Func):
3593class ArrayContains(Binary, Func):
3594    pass
class ArrayContained(Binary):
3597class ArrayContained(Binary):
3598    pass
class ArrayFilter(Func):
3601class ArrayFilter(Func):
3602    arg_types = {"this": True, "expression": True}
3603    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3606class ArrayJoin(Func):
3607    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3610class ArraySize(Func):
3611    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3614class ArraySort(Func):
3615    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3618class ArraySum(Func):
3619    pass
class ArrayUnionAgg(AggFunc):
3622class ArrayUnionAgg(AggFunc):
3623    pass
class Avg(AggFunc):
3626class Avg(AggFunc):
3627    pass
class AnyValue(AggFunc):
3630class AnyValue(AggFunc):
3631    pass
class Case(Func):
3634class Case(Func):
3635    arg_types = {"this": False, "ifs": True, "default": False}
3636
3637    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3638        instance = _maybe_copy(self, copy)
3639        instance.append(
3640            "ifs",
3641            If(
3642                this=maybe_parse(condition, copy=copy, **opts),
3643                true=maybe_parse(then, copy=copy, **opts),
3644            ),
3645        )
3646        return instance
3647
3648    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3649        instance = _maybe_copy(self, copy)
3650        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3651        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3637    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3638        instance = _maybe_copy(self, copy)
3639        instance.append(
3640            "ifs",
3641            If(
3642                this=maybe_parse(condition, copy=copy, **opts),
3643                true=maybe_parse(then, copy=copy, **opts),
3644            ),
3645        )
3646        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3648    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3649        instance = _maybe_copy(self, copy)
3650        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3651        return instance
class Cast(Func):
3654class Cast(Func):
3655    arg_types = {"this": True, "to": True}
3656
3657    @property
3658    def name(self) -> str:
3659        return self.this.name
3660
3661    @property
3662    def to(self):
3663        return self.args["to"]
3664
3665    @property
3666    def output_name(self):
3667        return self.name
3668
3669    def is_type(self, dtype: DataType.Type) -> bool:
3670        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3669    def is_type(self, dtype: DataType.Type) -> bool:
3670        return self.to.is_type(dtype)
class CastToStrType(Func):
3673class CastToStrType(Func):
3674    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3677class Collate(Binary):
3678    pass
class TryCast(Cast):
3681class TryCast(Cast):
3682    pass
class Ceil(Func):
3685class Ceil(Func):
3686    arg_types = {"this": True, "decimals": False}
3687    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3690class Coalesce(Func):
3691    arg_types = {"this": True, "expressions": False}
3692    is_var_len_args = True
class Concat(Func):
3695class Concat(Func):
3696    arg_types = {"expressions": True}
3697    is_var_len_args = True
class ConcatWs(Concat):
3700class ConcatWs(Concat):
3701    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3704class Count(AggFunc):
3705    arg_types = {"this": False}
class CountIf(AggFunc):
3708class CountIf(AggFunc):
3709    pass
class CurrentDate(Func):
3712class CurrentDate(Func):
3713    arg_types = {"this": False}
class CurrentDatetime(Func):
3716class CurrentDatetime(Func):
3717    arg_types = {"this": False}
class CurrentTime(Func):
3720class CurrentTime(Func):
3721    arg_types = {"this": False}
class CurrentTimestamp(Func):
3724class CurrentTimestamp(Func):
3725    arg_types = {"this": False}
class CurrentUser(Func):
3728class CurrentUser(Func):
3729    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3732class DateAdd(Func, TimeUnit):
3733    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3736class DateSub(Func, TimeUnit):
3737    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3740class DateDiff(Func, TimeUnit):
3741    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3742    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3745class DateTrunc(Func):
3746    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3749class DatetimeAdd(Func, TimeUnit):
3750    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3753class DatetimeSub(Func, TimeUnit):
3754    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3757class DatetimeDiff(Func, TimeUnit):
3758    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3761class DatetimeTrunc(Func, TimeUnit):
3762    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3765class DayOfWeek(Func):
3766    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3769class DayOfMonth(Func):
3770    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3773class DayOfYear(Func):
3774    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3777class WeekOfYear(Func):
3778    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3781class LastDateOfMonth(Func):
3782    pass
class Extract(Func):
3785class Extract(Func):
3786    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3789class TimestampAdd(Func, TimeUnit):
3790    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3793class TimestampSub(Func, TimeUnit):
3794    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3797class TimestampDiff(Func, TimeUnit):
3798    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3801class TimestampTrunc(Func, TimeUnit):
3802    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3805class TimeAdd(Func, TimeUnit):
3806    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3809class TimeSub(Func, TimeUnit):
3810    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3813class TimeDiff(Func, TimeUnit):
3814    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3817class TimeTrunc(Func, TimeUnit):
3818    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3821class DateFromParts(Func):
3822    _sql_names = ["DATEFROMPARTS"]
3823    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3826class DateStrToDate(Func):
3827    pass
class DateToDateStr(Func):
3830class DateToDateStr(Func):
3831    pass
class DateToDi(Func):
3834class DateToDi(Func):
3835    pass
class Day(Func):
3838class Day(Func):
3839    pass
class Decode(Func):
3842class Decode(Func):
3843    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3846class DiToDate(Func):
3847    pass
class Encode(Func):
3850class Encode(Func):
3851    arg_types = {"this": True, "charset": True}
class Exp(Func):
3854class Exp(Func):
3855    pass
class Explode(Func):
3858class Explode(Func):
3859    pass
class Floor(Func):
3862class Floor(Func):
3863    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3866class FromBase64(Func):
3867    pass
class ToBase64(Func):
3870class ToBase64(Func):
3871    pass
class Greatest(Func):
3874class Greatest(Func):
3875    arg_types = {"this": True, "expressions": False}
3876    is_var_len_args = True
class GroupConcat(Func):
3879class GroupConcat(Func):
3880    arg_types = {"this": True, "separator": False}
class Hex(Func):
3883class Hex(Func):
3884    pass
class If(Func):
3887class If(Func):
3888    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3891class IfNull(Func):
3892    arg_types = {"this": True, "expression": False}
3893    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3896class Initcap(Func):
3897    pass
class JSONKeyValue(Expression):
3900class JSONKeyValue(Expression):
3901    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3904class JSONObject(Func):
3905    arg_types = {
3906        "expressions": False,
3907        "null_handling": False,
3908        "unique_keys": False,
3909        "return_type": False,
3910        "format_json": False,
3911        "encoding": False,
3912    }
class OpenJSONColumnDef(Expression):
3915class OpenJSONColumnDef(Expression):
3916    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
3919class OpenJSON(Func):
3920    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
3923class JSONBContains(Binary):
3924    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3927class JSONExtract(Binary, Func):
3928    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3931class JSONExtractScalar(JSONExtract):
3932    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3935class JSONBExtract(JSONExtract):
3936    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3939class JSONBExtractScalar(JSONExtract):
3940    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3943class JSONFormat(Func):
3944    arg_types = {"this": False, "options": False}
3945    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3948class Least(Func):
3949    arg_types = {"expressions": False}
3950    is_var_len_args = True
class Length(Func):
3953class Length(Func):
3954    pass
class Levenshtein(Func):
3957class Levenshtein(Func):
3958    arg_types = {
3959        "this": True,
3960        "expression": False,
3961        "ins_cost": False,
3962        "del_cost": False,
3963        "sub_cost": False,
3964    }
class Ln(Func):
3967class Ln(Func):
3968    pass
class Log(Func):
3971class Log(Func):
3972    arg_types = {"this": True, "expression": False}
class Log2(Func):
3975class Log2(Func):
3976    pass
class Log10(Func):
3979class Log10(Func):
3980    pass
class LogicalOr(AggFunc):
3983class LogicalOr(AggFunc):
3984    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3987class LogicalAnd(AggFunc):
3988    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3991class Lower(Func):
3992    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3995class Map(Func):
3996    arg_types = {"keys": False, "values": False}
class StarMap(Func):
3999class StarMap(Func):
4000    pass
class VarMap(Func):
4003class VarMap(Func):
4004    arg_types = {"keys": True, "values": True}
4005    is_var_len_args = True
class MatchAgainst(Func):
4009class MatchAgainst(Func):
4010    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4013class Max(AggFunc):
4014    arg_types = {"this": True, "expressions": False}
4015    is_var_len_args = True
class MD5(Func):
4018class MD5(Func):
4019    _sql_names = ["MD5"]
class Min(AggFunc):
4022class Min(AggFunc):
4023    arg_types = {"this": True, "expressions": False}
4024    is_var_len_args = True
class Month(Func):
4027class Month(Func):
4028    pass
class Nvl2(Func):
4031class Nvl2(Func):
4032    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4035class Posexplode(Func):
4036    pass
class Pow(Binary, Func):
4039class Pow(Binary, Func):
4040    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4043class PercentileCont(AggFunc):
4044    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4047class PercentileDisc(AggFunc):
4048    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4051class Quantile(AggFunc):
4052    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4055class ApproxQuantile(Quantile):
4056    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4059class RangeN(Func):
4060    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4063class ReadCSV(Func):
4064    _sql_names = ["READ_CSV"]
4065    is_var_len_args = True
4066    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4069class Reduce(Func):
4070    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4073class RegexpExtract(Func):
4074    arg_types = {
4075        "this": True,
4076        "expression": True,
4077        "position": False,
4078        "occurrence": False,
4079        "group": False,
4080    }
class RegexpLike(Func):
4083class RegexpLike(Func):
4084    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4087class RegexpILike(Func):
4088    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4093class RegexpSplit(Func):
4094    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4097class Repeat(Func):
4098    arg_types = {"this": True, "times": True}
class Round(Func):
4101class Round(Func):
4102    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4105class RowNumber(Func):
4106    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4109class SafeDivide(Func):
4110    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4113class SetAgg(AggFunc):
4114    pass
class SHA(Func):
4117class SHA(Func):
4118    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4121class SHA2(Func):
4122    _sql_names = ["SHA2"]
4123    arg_types = {"this": True, "length": False}
class SortArray(Func):
4126class SortArray(Func):
4127    arg_types = {"this": True, "asc": False}
class Split(Func):
4130class Split(Func):
4131    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4136class Substring(Func):
4137    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4140class StandardHash(Func):
4141    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4144class StrPosition(Func):
4145    arg_types = {
4146        "this": True,
4147        "substr": True,
4148        "position": False,
4149        "instance": False,
4150    }
class StrToDate(Func):
4153class StrToDate(Func):
4154    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4157class StrToTime(Func):
4158    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4163class StrToUnix(Func):
4164    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4167class NumberToStr(Func):
4168    arg_types = {"this": True, "format": True}
class Struct(Func):
4171class Struct(Func):
4172    arg_types = {"expressions": True}
4173    is_var_len_args = True
class StructExtract(Func):
4176class StructExtract(Func):
4177    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4180class Sum(AggFunc):
4181    pass
class Sqrt(Func):
4184class Sqrt(Func):
4185    pass
class Stddev(AggFunc):
4188class Stddev(AggFunc):
4189    pass
class StddevPop(AggFunc):
4192class StddevPop(AggFunc):
4193    pass
class StddevSamp(AggFunc):
4196class StddevSamp(AggFunc):
4197    pass
class TimeToStr(Func):
4200class TimeToStr(Func):
4201    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4204class TimeToTimeStr(Func):
4205    pass
class TimeToUnix(Func):
4208class TimeToUnix(Func):
4209    pass
class TimeStrToDate(Func):
4212class TimeStrToDate(Func):
4213    pass
class TimeStrToTime(Func):
4216class TimeStrToTime(Func):
4217    pass
class TimeStrToUnix(Func):
4220class TimeStrToUnix(Func):
4221    pass
class Trim(Func):
4224class Trim(Func):
4225    arg_types = {
4226        "this": True,
4227        "expression": False,
4228        "position": False,
4229        "collation": False,
4230    }
class TsOrDsAdd(Func, TimeUnit):
4233class TsOrDsAdd(Func, TimeUnit):
4234    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4237class TsOrDsToDateStr(Func):
4238    pass
class TsOrDsToDate(Func):
4241class TsOrDsToDate(Func):
4242    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4245class TsOrDiToDi(Func):
4246    pass
class Unhex(Func):
4249class Unhex(Func):
4250    pass
class UnixToStr(Func):
4253class UnixToStr(Func):
4254    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4259class UnixToTime(Func):
4260    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4261
4262    SECONDS = Literal.string("seconds")
4263    MILLIS = Literal.string("millis")
4264    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4267class UnixToTimeStr(Func):
4268    pass
class Upper(Func):
4271class Upper(Func):
4272    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4275class Variance(AggFunc):
4276    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4279class VariancePop(AggFunc):
4280    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4283class Week(Func):
4284    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4287class XMLTable(Func):
4288    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4291class Year(Func):
4292    pass
class Use(Expression):
4295class Use(Expression):
4296    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4299class Merge(Expression):
4300    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4303class When(Func):
4304    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4309class NextValueFor(Func):
4310    arg_types = {"this": True, "order": False}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4347def maybe_parse(
4348    sql_or_expression: ExpOrStr,
4349    *,
4350    into: t.Optional[IntoType] = None,
4351    dialect: DialectType = None,
4352    prefix: t.Optional[str] = None,
4353    copy: bool = False,
4354    **opts,
4355) -> Expression:
4356    """Gracefully handle a possible string or expression.
4357
4358    Example:
4359        >>> maybe_parse("1")
4360        (LITERAL this: 1, is_string: False)
4361        >>> maybe_parse(to_identifier("x"))
4362        (IDENTIFIER this: x, quoted: False)
4363
4364    Args:
4365        sql_or_expression: the SQL code string or an expression
4366        into: the SQLGlot Expression to parse into
4367        dialect: the dialect used to parse the input expressions (in the case that an
4368            input expression is a SQL string).
4369        prefix: a string to prefix the sql with before it gets parsed
4370            (automatically includes a space)
4371        copy: whether or not to copy the expression.
4372        **opts: other options to use to parse the input expressions (again, in the case
4373            that an input expression is a SQL string).
4374
4375    Returns:
4376        Expression: the parsed or given expression.
4377    """
4378    if isinstance(sql_or_expression, Expression):
4379        if copy:
4380            return sql_or_expression.copy()
4381        return sql_or_expression
4382
4383    import sqlglot
4384
4385    sql = str(sql_or_expression)
4386    if prefix:
4387        sql = f"{prefix} {sql}"
4388    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4536def union(left, right, distinct=True, dialect=None, **opts):
4537    """
4538    Initializes a syntax tree from one UNION expression.
4539
4540    Example:
4541        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4542        'SELECT * FROM foo UNION SELECT * FROM bla'
4543
4544    Args:
4545        left (str | Expression): the SQL code string corresponding to the left-hand side.
4546            If an `Expression` instance is passed, it will be used as-is.
4547        right (str | Expression): the SQL code string corresponding to the right-hand side.
4548            If an `Expression` instance is passed, it will be used as-is.
4549        distinct (bool): set the DISTINCT flag if and only if this is true.
4550        dialect (str): the dialect used to parse the input expression.
4551        opts (kwargs): other options to use to parse the input expressions.
4552    Returns:
4553        Union: the syntax tree for the UNION expression.
4554    """
4555    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4556    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4557
4558    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4561def intersect(left, right, distinct=True, dialect=None, **opts):
4562    """
4563    Initializes a syntax tree from one INTERSECT expression.
4564
4565    Example:
4566        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4567        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4568
4569    Args:
4570        left (str | Expression): the SQL code string corresponding to the left-hand side.
4571            If an `Expression` instance is passed, it will be used as-is.
4572        right (str | Expression): the SQL code string corresponding to the right-hand side.
4573            If an `Expression` instance is passed, it will be used as-is.
4574        distinct (bool): set the DISTINCT flag if and only if this is true.
4575        dialect (str): the dialect used to parse the input expression.
4576        opts (kwargs): other options to use to parse the input expressions.
4577    Returns:
4578        Intersect: the syntax tree for the INTERSECT expression.
4579    """
4580    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4581    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4582
4583    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4586def except_(left, right, distinct=True, dialect=None, **opts):
4587    """
4588    Initializes a syntax tree from one EXCEPT expression.
4589
4590    Example:
4591        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4592        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4593
4594    Args:
4595        left (str | Expression): the SQL code string corresponding to the left-hand side.
4596            If an `Expression` instance is passed, it will be used as-is.
4597        right (str | Expression): the SQL code string corresponding to the right-hand side.
4598            If an `Expression` instance is passed, it will be used as-is.
4599        distinct (bool): set the DISTINCT flag if and only if this is true.
4600        dialect (str): the dialect used to parse the input expression.
4601        opts (kwargs): other options to use to parse the input expressions.
4602    Returns:
4603        Except: the syntax tree for the EXCEPT statement.
4604    """
4605    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4606    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4607
4608    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4611def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4612    """
4613    Initializes a syntax tree from one or multiple SELECT expressions.
4614
4615    Example:
4616        >>> select("col1", "col2").from_("tbl").sql()
4617        'SELECT col1, col2 FROM tbl'
4618
4619    Args:
4620        *expressions: the SQL code string to parse as the expressions of a
4621            SELECT statement. If an Expression instance is passed, this is used as-is.
4622        dialect: the dialect used to parse the input expressions (in the case that an
4623            input expression is a SQL string).
4624        **opts: other options to use to parse the input expressions (again, in the case
4625            that an input expression is a SQL string).
4626
4627    Returns:
4628        Select: the syntax tree for the SELECT statement.
4629    """
4630    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4633def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4634    """
4635    Initializes a syntax tree from a FROM expression.
4636
4637    Example:
4638        >>> from_("tbl").select("col1", "col2").sql()
4639        'SELECT col1, col2 FROM tbl'
4640
4641    Args:
4642        *expression: the SQL code string to parse as the FROM expressions of a
4643            SELECT statement. If an Expression instance is passed, this is used as-is.
4644        dialect: the dialect used to parse the input expression (in the case that the
4645            input expression is a SQL string).
4646        **opts: other options to use to parse the input expressions (again, in the case
4647            that the input expression is a SQL string).
4648
4649    Returns:
4650        Select: the syntax tree for the SELECT statement.
4651    """
4652    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4655def update(
4656    table: str | Table,
4657    properties: dict,
4658    where: t.Optional[ExpOrStr] = None,
4659    from_: t.Optional[ExpOrStr] = None,
4660    dialect: DialectType = None,
4661    **opts,
4662) -> Update:
4663    """
4664    Creates an update statement.
4665
4666    Example:
4667        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4668        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4669
4670    Args:
4671        *properties: dictionary of properties to set which are
4672            auto converted to sql objects eg None -> NULL
4673        where: sql conditional parsed into a WHERE statement
4674        from_: sql statement parsed into a FROM statement
4675        dialect: the dialect used to parse the input expressions.
4676        **opts: other options to use to parse the input expressions.
4677
4678    Returns:
4679        Update: the syntax tree for the UPDATE statement.
4680    """
4681    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4682    update_expr.set(
4683        "expressions",
4684        [
4685            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4686            for k, v in properties.items()
4687        ],
4688    )
4689    if from_:
4690        update_expr.set(
4691            "from",
4692            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4693        )
4694    if isinstance(where, Condition):
4695        where = Where(this=where)
4696    if where:
4697        update_expr.set(
4698            "where",
4699            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4700        )
4701    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4704def delete(
4705    table: ExpOrStr,
4706    where: t.Optional[ExpOrStr] = None,
4707    returning: t.Optional[ExpOrStr] = None,
4708    dialect: DialectType = None,
4709    **opts,
4710) -> Delete:
4711    """
4712    Builds a delete statement.
4713
4714    Example:
4715        >>> delete("my_table", where="id > 1").sql()
4716        'DELETE FROM my_table WHERE id > 1'
4717
4718    Args:
4719        where: sql conditional parsed into a WHERE statement
4720        returning: sql conditional parsed into a RETURNING statement
4721        dialect: the dialect used to parse the input expressions.
4722        **opts: other options to use to parse the input expressions.
4723
4724    Returns:
4725        Delete: the syntax tree for the DELETE statement.
4726    """
4727    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4728    if where:
4729        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4730    if returning:
4731        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4732    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition( expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Condition:
4735def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4736    """
4737    Initialize a logical condition expression.
4738
4739    Example:
4740        >>> condition("x=1").sql()
4741        'x = 1'
4742
4743        This is helpful for composing larger logical syntax trees:
4744        >>> where = condition("x=1")
4745        >>> where = where.and_("y=1")
4746        >>> Select().from_("tbl").select("*").where(where).sql()
4747        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4748
4749    Args:
4750        *expression (str | Expression): the SQL code string to parse.
4751            If an Expression instance is passed, this is used as-is.
4752        dialect (str): the dialect used to parse the input expression (in the case that the
4753            input expression is a SQL string).
4754        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4755        **opts: other options to use to parse the input expressions (again, in the case
4756            that the input expression is a SQL string).
4757
4758    Returns:
4759        Condition: the expression
4760    """
4761    return maybe_parse(  # type: ignore
4762        expression,
4763        into=Condition,
4764        dialect=dialect,
4765        copy=copy,
4766        **opts,
4767    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy (bool): Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.And:
4770def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4771    """
4772    Combine multiple conditions with an AND logical operator.
4773
4774    Example:
4775        >>> and_("x=1", and_("y=1", "z=1")).sql()
4776        'x = 1 AND (y = 1 AND z = 1)'
4777
4778    Args:
4779        *expressions (str | Expression): the SQL code strings to parse.
4780            If an Expression instance is passed, this is used as-is.
4781        dialect (str): the dialect used to parse the input expression.
4782        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4783        **opts: other options to use to parse the input expressions.
4784
4785    Returns:
4786        And: the new condition
4787    """
4788    return _combine(expressions, And, dialect, copy=copy, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.Or:
4791def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4792    """
4793    Combine multiple conditions with an OR logical operator.
4794
4795    Example:
4796        >>> or_("x=1", or_("y=1", "z=1")).sql()
4797        'x = 1 OR (y = 1 OR z = 1)'
4798
4799    Args:
4800        *expressions (str | Expression): the SQL code strings to parse.
4801            If an Expression instance is passed, this is used as-is.
4802        dialect (str): the dialect used to parse the input expression.
4803        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4804        **opts: other options to use to parse the input expressions.
4805
4806    Returns:
4807        Or: the new condition
4808    """
4809    return _combine(expressions, Or, dialect, copy=copy, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Not:
4812def not_(expression, dialect=None, copy=True, **opts) -> Not:
4813    """
4814    Wrap a condition with a NOT operator.
4815
4816    Example:
4817        >>> not_("this_suit='black'").sql()
4818        "NOT this_suit = 'black'"
4819
4820    Args:
4821        expression (str | Expression): the SQL code strings to parse.
4822            If an Expression instance is passed, this is used as-is.
4823        dialect (str): the dialect used to parse the input expression.
4824        **opts: other options to use to parse the input expressions.
4825
4826    Returns:
4827        Not: the new condition
4828    """
4829    this = condition(
4830        expression,
4831        dialect=dialect,
4832        copy=copy,
4833        **opts,
4834    )
4835    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression, copy=True) -> sqlglot.expressions.Paren:
4838def paren(expression, copy=True) -> Paren:
4839    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None, copy=True):
4857def to_identifier(name, quoted=None, copy=True):
4858    """Builds an identifier.
4859
4860    Args:
4861        name: The name to turn into an identifier.
4862        quoted: Whether or not force quote the identifier.
4863        copy: Whether or not to copy a passed in Identefier node.
4864
4865    Returns:
4866        The identifier ast node.
4867    """
4868
4869    if name is None:
4870        return None
4871
4872    if isinstance(name, Identifier):
4873        identifier = _maybe_copy(name, copy)
4874    elif isinstance(name, str):
4875        identifier = Identifier(
4876            this=name,
4877            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4878        )
4879    else:
4880        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4881    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4887def to_interval(interval: str | Literal) -> Interval:
4888    """Builds an interval expression from a string like '1 day' or '5 months'."""
4889    if isinstance(interval, Literal):
4890        if not interval.is_string:
4891            raise ValueError("Invalid interval string.")
4892
4893        interval = interval.this
4894
4895    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4896
4897    if not interval_parts:
4898        raise ValueError("Invalid interval string.")
4899
4900    return Interval(
4901        this=Literal.string(interval_parts.group(1)),
4902        unit=Var(this=interval_parts.group(2)),
4903    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4916def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4917    """
4918    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4919    If a table is passed in then that table is returned.
4920
4921    Args:
4922        sql_path: a `[catalog].[schema].[table]` string.
4923
4924    Returns:
4925        A table expression.
4926    """
4927    if sql_path is None or isinstance(sql_path, Table):
4928        return sql_path
4929    if not isinstance(sql_path, str):
4930        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4931
4932    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4933    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4936def to_column(sql_path: str | Column, **kwargs) -> Column:
4937    """
4938    Create a column from a `[table].[column]` sql path. Schema is optional.
4939
4940    If a column is passed in then that column is returned.
4941
4942    Args:
4943        sql_path: `[table].[column]` string
4944    Returns:
4945        Table: A column expression
4946    """
4947    if sql_path is None or isinstance(sql_path, Column):
4948        return sql_path
4949    if not isinstance(sql_path, str):
4950        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4951    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
4954def alias_(
4955    expression: ExpOrStr,
4956    alias: str | Identifier,
4957    table: bool | t.Sequence[str | Identifier] = False,
4958    quoted: t.Optional[bool] = None,
4959    dialect: DialectType = None,
4960    copy: bool = True,
4961    **opts,
4962):
4963    """Create an Alias expression.
4964
4965    Example:
4966        >>> alias_('foo', 'bar').sql()
4967        'foo AS bar'
4968
4969        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4970        '(SELECT 1, 2) AS bar(a, b)'
4971
4972    Args:
4973        expression: the SQL code strings to parse.
4974            If an Expression instance is passed, this is used as-is.
4975        alias: the alias name to use. If the name has
4976            special characters it is quoted.
4977        table: Whether or not to create a table alias, can also be a list of columns.
4978        quoted: whether or not to quote the alias
4979        dialect: the dialect used to parse the input expression.
4980        copy: Whether or not to copy the expression.
4981        **opts: other options to use to parse the input expressions.
4982
4983    Returns:
4984        Alias: the aliased expression
4985    """
4986    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4987    alias = to_identifier(alias, quoted=quoted)
4988
4989    if table:
4990        table_alias = TableAlias(this=alias)
4991        exp.set("alias", table_alias)
4992
4993        if not isinstance(table, bool):
4994            for column in table:
4995                table_alias.append("columns", to_identifier(column, quoted=quoted))
4996
4997        return exp
4998
4999    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5000    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5001    # for the complete Window expression.
5002    #
5003    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5004
5005    if "alias" in exp.arg_types and not isinstance(exp, Window):
5006        exp.set("alias", alias)
5007        return exp
5008    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
5011def subquery(expression, alias=None, dialect=None, **opts):
5012    """
5013    Build a subquery expression.
5014
5015    Example:
5016        >>> subquery('select x from tbl', 'bar').select('x').sql()
5017        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5018
5019    Args:
5020        expression (str | Expression): the SQL code strings to parse.
5021            If an Expression instance is passed, this is used as-is.
5022        alias (str | Expression): the alias name to use.
5023        dialect (str): the dialect used to parse the input expression.
5024        **opts: other options to use to parse the input expressions.
5025
5026    Returns:
5027        Select: a new select with the subquery expression included
5028    """
5029
5030    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5031    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5034def column(
5035    col: str | Identifier,
5036    table: t.Optional[str | Identifier] = None,
5037    db: t.Optional[str | Identifier] = None,
5038    catalog: t.Optional[str | Identifier] = None,
5039    quoted: t.Optional[bool] = None,
5040) -> Column:
5041    """
5042    Build a Column.
5043
5044    Args:
5045        col: column name
5046        table: table name
5047        db: db name
5048        catalog: catalog name
5049        quoted: whether or not to force quote each part
5050    Returns:
5051        Column: column instance
5052    """
5053    return Column(
5054        this=to_identifier(col, quoted=quoted),
5055        table=to_identifier(table, quoted=quoted),
5056        db=to_identifier(db, quoted=quoted),
5057        catalog=to_identifier(catalog, quoted=quoted),
5058    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5061def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5062    """Cast an expression to a data type.
5063
5064    Example:
5065        >>> cast('x + 1', 'int').sql()
5066        'CAST(x + 1 AS INT)'
5067
5068    Args:
5069        expression: The expression to cast.
5070        to: The datatype to cast to.
5071
5072    Returns:
5073        A cast node.
5074    """
5075    expression = maybe_parse(expression, **opts)
5076    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
5079def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5080    """Build a Table.
5081
5082    Args:
5083        table (str | Expression): column name
5084        db (str | Expression): db name
5085        catalog (str | Expression): catalog name
5086
5087    Returns:
5088        Table: table instance
5089    """
5090    return Table(
5091        this=to_identifier(table, quoted=quoted),
5092        db=to_identifier(db, quoted=quoted),
5093        catalog=to_identifier(catalog, quoted=quoted),
5094        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5095    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5098def values(
5099    values: t.Iterable[t.Tuple[t.Any, ...]],
5100    alias: t.Optional[str] = None,
5101    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5102) -> Values:
5103    """Build VALUES statement.
5104
5105    Example:
5106        >>> values([(1, '2')]).sql()
5107        "VALUES (1, '2')"
5108
5109    Args:
5110        values: values statements that will be converted to SQL
5111        alias: optional alias
5112        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5113         If either are provided then an alias is also required.
5114
5115    Returns:
5116        Values: the Values expression object
5117    """
5118    if columns and not alias:
5119        raise ValueError("Alias is required when providing columns")
5120
5121    return Values(
5122        expressions=[convert(tup) for tup in values],
5123        alias=(
5124            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5125            if columns
5126            else (TableAlias(this=to_identifier(alias)) if alias else None)
5127        ),
5128    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5131def var(name: t.Optional[ExpOrStr]) -> Var:
5132    """Build a SQL variable.
5133
5134    Example:
5135        >>> repr(var('x'))
5136        '(VAR this: x)'
5137
5138        >>> repr(var(column('x', table='y')))
5139        '(VAR this: x)'
5140
5141    Args:
5142        name: The name of the var or an expression who's name will become the var.
5143
5144    Returns:
5145        The new variable node.
5146    """
5147    if not name:
5148        raise ValueError("Cannot convert empty name into var.")
5149
5150    if isinstance(name, Expression):
5151        name = name.name
5152    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5155def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5156    """Build ALTER TABLE... RENAME... expression
5157
5158    Args:
5159        old_name: The old name of the table
5160        new_name: The new name of the table
5161
5162    Returns:
5163        Alter table expression
5164    """
5165    old_table = to_table(old_name)
5166    new_table = to_table(new_name)
5167    return AlterTable(
5168        this=old_table,
5169        actions=[
5170            RenameTable(this=new_table),
5171        ],
5172    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5175def convert(value: t.Any, copy: bool = False) -> Expression:
5176    """Convert a python value into an expression object.
5177
5178    Raises an error if a conversion is not possible.
5179
5180    Args:
5181        value: A python object.
5182        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5183
5184    Returns:
5185        Expression: the equivalent expression object.
5186    """
5187    if isinstance(value, Expression):
5188        return _maybe_copy(value, copy)
5189    if isinstance(value, str):
5190        return Literal.string(value)
5191    if isinstance(value, bool):
5192        return Boolean(this=value)
5193    if value is None or (isinstance(value, float) and math.isnan(value)):
5194        return NULL
5195    if isinstance(value, numbers.Number):
5196        return Literal.number(value)
5197    if isinstance(value, datetime.datetime):
5198        datetime_literal = Literal.string(
5199            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5200        )
5201        return TimeStrToTime(this=datetime_literal)
5202    if isinstance(value, datetime.date):
5203        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5204        return DateStrToDate(this=date_literal)
5205    if isinstance(value, tuple):
5206        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5207    if isinstance(value, list):
5208        return Array(expressions=[convert(v, copy=copy) for v in value])
5209    if isinstance(value, dict):
5210        return Map(
5211            keys=[convert(k, copy=copy) for k in value],
5212            values=[convert(v, copy=copy) for v in value.values()],
5213        )
5214    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children(expression, fun, *args, **kwargs):
5217def replace_children(expression, fun, *args, **kwargs):
5218    """
5219    Replace children of an expression with the result of a lambda fun(child) -> exp.
5220    """
5221    for k, v in expression.args.items():
5222        is_list_arg = type(v) is list
5223
5224        child_nodes = v if is_list_arg else [v]
5225        new_child_nodes = []
5226
5227        for cn in child_nodes:
5228            if isinstance(cn, Expression):
5229                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5230                    new_child_nodes.append(child_node)
5231                    child_node.parent = expression
5232                    child_node.arg_key = k
5233            else:
5234                new_child_nodes.append(cn)
5235
5236        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
5239def column_table_names(expression):
5240    """
5241    Return all table names referenced through columns in an expression.
5242
5243    Example:
5244        >>> import sqlglot
5245        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5246        ['c', 'a']
5247
5248    Args:
5249        expression (sqlglot.Expression): expression to find table names
5250
5251    Returns:
5252        list: A list of unique names
5253    """
5254    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
5257def table_name(table) -> str:
5258    """Get the full name of a table as a string.
5259
5260    Args:
5261        table (exp.Table | str): table expression node or string.
5262
5263    Examples:
5264        >>> from sqlglot import exp, parse_one
5265        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5266        'a.b.c'
5267
5268    Returns:
5269        The table name.
5270    """
5271
5272    table = maybe_parse(table, into=Table)
5273
5274    if not table:
5275        raise ValueError(f"Cannot parse {table}")
5276
5277    return ".".join(
5278        part
5279        for part in (
5280            table.text("catalog"),
5281            table.text("db"),
5282            table.name,
5283        )
5284        if part
5285    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
5288def replace_tables(expression, mapping):
5289    """Replace all tables in expression according to the mapping.
5290
5291    Args:
5292        expression (sqlglot.Expression): expression node to be transformed and replaced.
5293        mapping (Dict[str, str]): mapping of table names.
5294
5295    Examples:
5296        >>> from sqlglot import exp, parse_one
5297        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5298        'SELECT * FROM c'
5299
5300    Returns:
5301        The mapped expression.
5302    """
5303
5304    def _replace_tables(node):
5305        if isinstance(node, Table):
5306            new_name = mapping.get(table_name(node))
5307            if new_name:
5308                return to_table(
5309                    new_name,
5310                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5311                )
5312        return node
5313
5314    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
5317def replace_placeholders(expression, *args, **kwargs):
5318    """Replace placeholders in an expression.
5319
5320    Args:
5321        expression (sqlglot.Expression): expression node to be transformed and replaced.
5322        args: positional names that will substitute unnamed placeholders in the given order.
5323        kwargs: keyword arguments that will substitute named placeholders.
5324
5325    Examples:
5326        >>> from sqlglot import exp, parse_one
5327        >>> replace_placeholders(
5328        ...     parse_one("select * from :tbl where ? = ?"),
5329        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5330        ... ).sql()
5331        "SELECT * FROM foo WHERE str_col = 'b'"
5332
5333    Returns:
5334        The mapped expression.
5335    """
5336
5337    def _replace_placeholders(node, args, **kwargs):
5338        if isinstance(node, Placeholder):
5339            if node.name:
5340                new_name = kwargs.get(node.name)
5341                if new_name:
5342                    return convert(new_name)
5343            else:
5344                try:
5345                    return convert(next(args))
5346                except StopIteration:
5347                    pass
5348        return node
5349
5350    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5353def expand(
5354    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5355) -> Expression:
5356    """Transforms an expression by expanding all referenced sources into subqueries.
5357
5358    Examples:
5359        >>> from sqlglot import parse_one
5360        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5361        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5362
5363        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5364        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5365
5366    Args:
5367        expression: The expression to expand.
5368        sources: A dictionary of name to Subqueryables.
5369        copy: Whether or not to copy the expression during transformation. Defaults to True.
5370
5371    Returns:
5372        The transformed expression.
5373    """
5374
5375    def _expand(node: Expression):
5376        if isinstance(node, Table):
5377            name = table_name(node)
5378            source = sources.get(name)
5379            if source:
5380                subquery = source.subquery(node.alias or name)
5381                subquery.comments = [f"source: {name}"]
5382                return subquery.transform(_expand, copy=False)
5383        return node
5384
5385    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5388def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5389    """
5390    Returns a Func expression.
5391
5392    Examples:
5393        >>> func("abs", 5).sql()
5394        'ABS(5)'
5395
5396        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5397        'CAST(5 AS DOUBLE)'
5398
5399    Args:
5400        name: the name of the function to build.
5401        args: the args used to instantiate the function of interest.
5402        dialect: the source dialect.
5403        kwargs: the kwargs used to instantiate the function of interest.
5404
5405    Note:
5406        The arguments `args` and `kwargs` are mutually exclusive.
5407
5408    Returns:
5409        An instance of the function of interest, or an anonymous function, if `name` doesn't
5410        correspond to an existing `sqlglot.expressions.Func` class.
5411    """
5412    if args and kwargs:
5413        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5414
5415    from sqlglot.dialects.dialect import Dialect
5416
5417    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5418    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5419
5420    parser = Dialect.get_or_raise(dialect)().parser()
5421    from_args_list = parser.FUNCTIONS.get(name.upper())
5422
5423    if from_args_list:
5424        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5425    else:
5426        kwargs = kwargs or {"expressions": converted}
5427        function = Anonymous(this=name, **kwargs)
5428
5429    for error_message in function.error_messages(converted):
5430        raise ValueError(error_message)
5431
5432    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5435def true():
5436    """
5437    Returns a true Boolean expression.
5438    """
5439    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5442def false():
5443    """
5444    Returns a false Boolean expression.
5445    """
5446    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5449def null():
5450    """
5451    Returns a Null expression.
5452    """
5453    return Null()

Returns a Null expression.